Skip to contentSkip to conversation

media: apple: add avd driver

PATCH New Sofus Forstreuter 2 participants 33 messages Nov 28

Subsystems (4)
lore
Share & tools
lore
#0 lore raw

v4 cover media: apple: add avd driver

Hi,

This series enables hardware video decoding on Apple Silicon M1, M2 and M3 SoCs. It adds support for all the codecs AVD (Apple Video Decoder) supports, which is H264, H265, VP9 and AV1 (only on M3+).

The AVD is a bit unique both as a video decoder and an IP block on Apple Silicon SoCs. Instead of following the normal "a register for each parameter", AVD is programmed through one single register. This means the order of the writes are important, but its also important to ensure we dont write faster than the hardware can process. To solve this, we use the included Cortex-M3 co-processor. The CM3 accepts unsigned code, which we take advantage off [1].
The driver prepares the instructions and writes them into segments, which are submitted to the CM3. The CM3 then programs the hardware and notifies the AP when the job is done or if an error occurred.

The firmware is still missing a few bits and pieces, but when that's settled it will be submitted to linux-firmware. Until then it should be build from source, which can be found on github [1].

The driver implements the V4L2 M2M stateless decoder API. The driver's framework is based very heavy on rkvdecs driver. It therefore comes as no suprise that v4l2-compliance reports no errors:
Total for avd device /dev/video0: 49, Succeeded: 49, Failed: 0, Warnings: 0

The fluster scores are:
JVT-AVC_V1: 77/135
JVT-FR-EXT: 42/69
VP9-TEST-VECTORS: 216/305
VP9-TEST-VECTORS-HIGH: 1/6
JCT-VC-HEVC_V1: 145/147
AV1-TEST-VECTORS: 238/242

Since not all unsupported H264 streams are rejected, the scores depend on the reset working, this only works with a patch to the apple-dart driver so that the IOMMU attach/detach trick works.

All codecs support 4:2:2, 4:2:0, in 10 and 8 bit. By default, AVD outputs in NV12, NV16, P010 and P210. Support for 4:4:4 and 12 bit formats has not been added yet.

Internally the AVD uses an Apple specific compressed and tiled format called Interchange to store reference image data. This is stored after image data across all codecs. Apple Interchange is used for sharing buffers with other hardware blocks (GPU, display controller). The V4L2 pixel formats have been added to help with calculating sizes.

This driver has been tested on most Apple Silicon SoCs in our downstream tree [2]. Its expected this driver will work on M4, M5, M6 and the Neo, with firmware already being written for all except the M6 SoCs [3].

The groundwork for this was laid many years ago by Jamie, R and Eileen, who through a combined effort managed to reverse engineer many core parts of the AVD block.
This driver would not have been possible without the work done by Eileen, who wrote initial support for H264, H265, VP9 and excellent tooling [4], allowing me to reverse engineer AV1 and make the driver conformant.

[1] https://github.com/sofus13/avd-fw/tree/avd-next-fw
[2] https://github.com/AsahiLinux/linux
[3] https://github.com/AsahiLinux/avd-fw
[4] https://github.com/eiln/avd/tree/main

---
Changes in v4:
- Mark devices as dma-coherent
- Updated dma handling
- Switched to vb2_dma_sg_memops
- Updated firmware
- Added the APPLE_AX* formats in pixfmt-reserved.rst
- Fix things reported by sashiko
- Pickup Nicolas's R-b
- Link to v3: https://patch.msgid.link/[email protected]

Changes in v3:
- Align output buffer (fixes 2 hevc tests)
- Renamed interchange formats
- Fix various bitmasks
- Fix minor things reported by sashiko
- Pickup Krzysztof and Neal's R-b
- Link to v2: https://patch.msgid.link/[email protected]

Changes in v2:
- Patch order
- Fixed dt-bindings by constraining all properties
- Fixed dts, add interrupts, iommus and regs. Drop labels, fix names
- Add Apple Interchange format
- Add more av1 and vp9 validation to v4l2-ctrls
- Validate more codec parameters
- Use the new CM3 firmware (drop avd-hw, drop submission loops)
- Updated cover to reflect changes
- Link to v1: https://patch.msgid.link/[email protected]

To: Sven Peter <[email protected]>
To: Janne Grunau <[email protected]>
To: Neal Gompa <[email protected]>
To: Mauro Carvalho Chehab <[email protected]>
To: Rob Herring <[email protected]>
To: Krzysztof Kozlowski <[email protected]>
To: Conor Dooley <[email protected]>
To: Sofus Forstreuter <[email protected]>
To: Philipp Zabel <[email protected]>
To: Heiko Stuebner <[email protected]>
Cc: [email protected]
Cc: [email protected]
Cc: [email protected]
Cc: [email protected]
Cc: [email protected]
Cc: [email protected]

---
Sofus Forstreuter (17):
dt-bindings: media: add apple,avd
media: v4l2: Add P210 pixel format
media: v4l2: Add Apple interchange pixel formats
media: v4l2-ctrls: validate AV1 context_update_tile_id
media: v4l2-ctrls: validate vp9 tile_rows_log2
media: apple: add avd driver
media: apple: avd: add h264 support
media: apple: avd: add vp9 support
media: apple: avd: add hevc support
media: apple: avd: add av1 support
arm64: dts: apple: t8103: add avd nodes
arm64: dts: apple: t8112: add avd nodes
arm64: dts: apple: t8122: add avd nodes
arm64: dts: apple: t600x: add avd nodes
arm64: dts: apple: t602x: add avd nodes
arm64: dts: apple: t6030: add avd nodes
arm64: dts: apple: t6031: add avd nodes

 .../devicetree/bindings/media/apple,avd.yaml       |  127 +
 .../userspace-api/media/v4l/pixfmt-reserved.rst    |   30 +
 .../userspace-api/media/v4l/pixfmt-yuv-planar.rst  |   14 +-
 MAINTAINERS                                        |    2 +
 arch/arm64/boot/dts/apple/t600x-dieX.dtsi          |   33 +
 arch/arm64/boot/dts/apple/t602x-dieX.dtsi          |   33 +
 arch/arm64/boot/dts/apple/t6030.dtsi               |   33 +
 arch/arm64/boot/dts/apple/t6031-dieX.dtsi          |   33 +
 arch/arm64/boot/dts/apple/t8103.dtsi               |   33 +
 arch/arm64/boot/dts/apple/t8112.dtsi               |   33 +
 arch/arm64/boot/dts/apple/t8122.dtsi               |   33 +
 drivers/media/platform/Kconfig                     |    1 +
 drivers/media/platform/Makefile                    |    1 +
 drivers/media/platform/apple/Kconfig               |    5 +
 drivers/media/platform/apple/Makefile              |    3 +
 drivers/media/platform/apple/avd/Kconfig           |   18 +
 drivers/media/platform/apple/avd/Makefile          |    5 +
 .../media/platform/apple/avd/avd-av1-entropymode.c | 4698 ++++++++++++++++++++
 .../media/platform/apple/avd/avd-av1-entropymode.h |  284 ++
 drivers/media/platform/apple/avd/avd-av1.c         | 1432 ++++++
 drivers/media/platform/apple/avd/avd-drv.c         |  881 ++++
 drivers/media/platform/apple/avd/avd-h264.c        |  849 ++++
 drivers/media/platform/apple/avd/avd-hevc.c        | 1327 ++++++
 drivers/media/platform/apple/avd/avd-inst.h        |  215 +
 drivers/media/platform/apple/avd/avd-v4l2.c        | 1031 +++++
 drivers/media/platform/apple/avd/avd-vp9.c         | 1047 +++++
 drivers/media/platform/apple/avd/avd.h             |  280 ++
 drivers/media/v4l2-core/v4l2-common.c              |    8 +
 drivers/media/v4l2-core/v4l2-ctrls-core.c          |   11 +-
 drivers/media/v4l2-core/v4l2-ioctl.c               |    7 +
 include/uapi/linux/v4l2-controls.h                 |    2 +-
 include/uapi/linux/videodev2.h                     |    9 +
 32 files changed, 12514 insertions(+), 4 deletions(-)

---
base-commit: fb8b2c10a588f1384b98280b1c32307da9db4747
change-id: 20260917-avd-7ee5474b468c

Best regards,

Signature · 1 line
Sofus Forstreuter <[email protected]>
#1 lore raw

PATCH v4 1/17 dt-bindings: media: add apple,avd

Document the Apple Video Decoder. A hardware video decoder present on Apple hardware.

---
 .../devicetree/bindings/media/apple,avd.yaml       | 127 +++++++++++++++++++++
 MAINTAINERS                                        |   1 +
 2 files changed, 128 insertions(+)
Documentation/devicetree/bindings/media/apple,avd.yaml new file +127 -0
new file mode 100644
index 000000000000..108b4971914a
@@ -0,0 +1,127 @@
+# SPDX-License-Identifier: GPL-2.0-only OR BSD-2-Clause
+%YAML 1.2
+---
+$id: http://devicetree.org/schemas/media/apple,avd.yaml#
+$schema: http://devicetree.org/meta-schemas/core.yaml#
+
+title: Apple Video Decoder (AVD)
+
+description: |
+  AVD is a stateless video decode IP block present on Apple devices.
+  Notably it includes an ARM Cortex-M3 and associated DMA controller.
+  AVD is capable of decoding H264, H265, VP9 and AV1 on newer SoCs.
+
+  The IP does not change much, with changes being mostly the CM3 having more
+  memory and interrupts.
+
+maintainers:
+  - Sofus Forstreuter <[email protected]>
+
+properties:
+  compatible:
+    oneOf:
+      - items:
+          - enum:
+              - apple,t6030-avd
+              - apple,t6031-avd
+          - const: apple,t8122-avd
+      - enum:
+          - apple,t6000-avd
+          - apple,t6020-avd
+          - apple,t8103-avd
+          - apple,t8112-avd
+          - apple,t8122-avd
+
+  reg:
+    items:
+      - description: DMA control
+      - description: Cortex-M3 code (unsigned)
+      - description: Cortex-M3 sram
+      - description: Mailbox
+      - description: Video decode control
+
+  reg-names:
+    items:
+      - const: piodma
+      - const: code
+      - const: sram
+      - const: mbox
+      - const: ctrl
+
+  iommus:
+    items:
+      - description: Decode related
+      - description: DMA controller
+
+  power-domains:
+    maxItems: 1
+
+  resets:
+    maxItems: 1
+
+  interrupts:
+    items:
+      - description: mailbox 0
+      - description: mailbox 1
+      - description: mailbox 2
+      - description: mailbox 3
+      - description: flag 0
+      - description: flag 1
+      - description: DMA status
+    description: |
+      Notably there are no decode related interrupts. All decode related
+      interrupts are sent to the CM3.
+
+  interrupt-names:
+    items:
+      - const: mbox0
+      - const: mbox1
+      - const: mbox2
+      - const: mbox3
+      - const: flag0
+      - const: flag1
+      - const: piodma
+
+required:
+  - compatible
+  - reg
+  - interrupts
+  - reg-names
+  - iommus
+  - power-domains
+  - resets
+
+additionalProperties: false
+
+examples:
+  - |
+    #include <dt-bindings/interrupt-controller/apple-aic.h>
+    #include <dt-bindings/interrupt-controller/irq.h>
+
+    soc {
+        #address-cells = <2>;
+        #size-cells = <2>;
+
+        video-codec@289070000 {
+            compatible = "apple,t8122-avd";
+            reg = <0x2 0x89070000 0x0 0x4000>,
+                  <0x2 0x89080000 0x0 0x10000>,
+                  <0x2 0x89092000 0x0 0x14000>,
+                  <0x2 0x890a4000 0x0 0x4000>,
+                  <0x2 0x89100000 0x0 0x10000>;
+            reg-names = "piodma", "code", "sram", "mbox", "ctrl";
+            interrupt-parent = <&aic>;
+            interrupts = <AIC_IRQ 679 IRQ_TYPE_LEVEL_HIGH>,
+                         <AIC_IRQ 680 IRQ_TYPE_LEVEL_HIGH>,
+                         <AIC_IRQ 681 IRQ_TYPE_LEVEL_HIGH>,
+                         <AIC_IRQ 682 IRQ_TYPE_LEVEL_HIGH>,
+                         <AIC_IRQ 683 IRQ_TYPE_LEVEL_HIGH>,
+                         <AIC_IRQ 684 IRQ_TYPE_LEVEL_HIGH>,
+                         <AIC_IRQ 685 IRQ_TYPE_LEVEL_HIGH>;
+            interrupt-names = "mbox0", "mbox1", "mbox2", "mbox3",
+                              "flag0", "flag1", "piodma";
+            power-domains = <&ps_avd_sys>;
+            resets = <&ps_avd_sys>;
+            iommus = <&avd_dart 0>, <&avd_dart 1>;
+        };
+    };
MAINTAINERS +1 -0
index f72ce07a4e38..5dd197078130 100644
@@ -2736,6 +2736,7 @@ F:	Documentation/devicetree/bindings/iommu/apple,dart.yaml
 F:	Documentation/devicetree/bindings/iommu/apple,sart.yaml
 F:	Documentation/devicetree/bindings/leds/backlight/apple,dwi-bl.yaml
 F:	Documentation/devicetree/bindings/mailbox/apple,mailbox.yaml
+F:	Documentation/devicetree/bindings/media/apple,avd.yaml
 F:	Documentation/devicetree/bindings/mfd/apple,smc.yaml
 F:	Documentation/devicetree/bindings/net/bluetooth/brcm,bcm4377-bluetooth.yaml
 F:	Documentation/devicetree/bindings/nvme/apple,nvme-ans.yaml
Signature · 1 line
2.56.0
#2 lore raw

Re: [PATCH v4 01/17] dt-bindings: media: add apple,avd

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Low] dt-bindings: media: apple,avd: non-canonical property ordering in schema --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Low] dt-bindings: media: apple,avd: non-canonical property ordering in schema
--

commit 6dddf7b0709b29099ef5104fe7e80f1684f9e301
Author: Sofus Forstreuter <[email protected]>

dt-bindings: media: add apple,avd

This commit adds the Device Tree binding schema for the Apple Video Decoder (AVD) IP block and updates MAINTAINERS.

Quoted 5 lines
Documentation/devicetree/bindings/media/apple,avd.yaml new file +0 -0
new file mode 100644
index 0000000000000..108b4971914ad

[ ... ]

Quoted 40 lines
Documentation/devicetree/bindings/media/apple,avd.yaml new file +40 -0
+  reg-names:
+    items:
+      - const: piodma
+      - const: code
+      - const: sram
+      - const: mbox
+      - const: ctrl
+
+  iommus:
+    items:
+      - description: Decode related
+      - description: DMA controller
+
+  power-domains:
+    maxItems: 1
+
+  resets:
+    maxItems: 1
+
+  interrupts:
+    items:
+      - description: mailbox 0
+      - description: mailbox 1
+      - description: mailbox 2
+      - description: mailbox 3
+      - description: flag 0
+      - description: flag 1
+      - description: DMA status
+    description: |
+      Notably there are no decode related interrupts. All decode related
+      interrupts are sent to the CM3.
+
+  interrupt-names:
+    items:
+      - const: mbox0
+      - const: mbox1
+      - const: mbox2
+      - const: mbox3
+      - const: flag0
+      - const: flag1

Documentation/devicetree/bindings/media/apple,avd.yaml line 92

Quoted 10 lines
Documentation/devicetree/bindings/media/apple,avd.yaml new file +10 -0
+      - const: piodma
+
+required:
+  - compatible
+  - reg
+  - interrupts
+  - reg-names
+  - iommus
+  - power-domains
+  - resets

[Severity: Low]
Could the properties and required lists use the canonical DT property ordering (compatible, reg, reg-names, interrupts, interrupt-names, power-domains, resets, iommus), matching the example node? Here properties places iommus, power-domains and resets before interrupts and interrupt-names, while required places interrupts between reg and reg-names.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
#3 lore raw

PATCH v4 2/17 media: v4l2: Add P210 pixel format

In reply to Sofus Forstreuter

P210 is a YUV format with 10-bits per component with interleaved UV.

---
 .../userspace-api/media/v4l/pixfmt-yuv-planar.rst          | 14 ++++++++++++--
 drivers/media/v4l2-core/v4l2-common.c                      |  1 +
 drivers/media/v4l2-core/v4l2-ioctl.c                       |  1 +
 include/uapi/linux/videodev2.h                             |  1 +
 4 files changed, 15 insertions(+), 2 deletions(-)
Documentation/userspace-api/media/v4l/pixfmt-yuv-planar.rst +12 -2
index 0631919bd667..f2d2e79698fa 100644
@@ -138,6 +138,13 @@ All components are stored with the same number of bits per component.
       - Cb, Cr
       - No
       - Linear
+    * - V4L2_PIX_FMT_P210
+      - 'P210'
+      - 10
+      - 4:2:2
+      - Cb, Cr
+      - Yes
+      - Linear
     * - V4L2_PIX_FMT_NV15
       - 'NV15'
       - 10
@@ -834,12 +841,15 @@ number of lines as the luma plane.
 
 .. _V4L2_PIX_FMT_P010:
 .. _V4L2-PIX-FMT-P010-4L4:
+.. _V4L2-PIX-FMT-P210:
 
-P010 and tiled P010
--------------------
+P010, tiled P010 and P210
+-------------------------
 
 P010 is like NV12 with 10 bits per component, expanded to 16 bits.
 Data in the 10 high bits, zeros in the 6 low bits, arranged in little endian order.
+P210 is the same as P010 but the chroma plane is only subsampled by 2 in the
+horizontal direction.
 
 .. flat-table:: Sample 4x4 P010 Image
     :header-rows:  0
drivers/media/v4l2-core/v4l2-common.c +1 -0
index 11ab684024c5..43ef12d073a3 100644
@@ -325,6 +325,7 @@ const struct v4l2_format_info *v4l2_format_info(u32 format)
 		{ .format = V4L2_PIX_FMT_NV42,    .pixel_enc = V4L2_PIXEL_ENC_YUV, .mem_planes = 1, .comp_planes = 2, .bpp = { 1, 2, 0, 0 }, .bpp_div = { 1, 1, 1, 1 }, .hdiv = 1, .vdiv = 1 },
 		{ .format = V4L2_PIX_FMT_P010,    .pixel_enc = V4L2_PIXEL_ENC_YUV, .mem_planes = 1, .comp_planes = 2, .bpp = { 2, 4, 0, 0 }, .bpp_div = { 1, 1, 1, 1 }, .hdiv = 2, .vdiv = 2 },
 		{ .format = V4L2_PIX_FMT_P012,    .pixel_enc = V4L2_PIXEL_ENC_YUV, .mem_planes = 1, .comp_planes = 2, .bpp = { 2, 4, 0, 0 }, .bpp_div = { 1, 1, 1, 1 }, .hdiv = 2, .vdiv = 2 },
+		{ .format = V4L2_PIX_FMT_P210,    .pixel_enc = V4L2_PIXEL_ENC_YUV, .mem_planes = 1, .comp_planes = 2, .bpp = { 2, 4, 0, 0 }, .bpp_div = { 1, 1, 1, 1 }, .hdiv = 2, .vdiv = 1 },
 
 		{ .format = V4L2_PIX_FMT_YUV410,  .pixel_enc = V4L2_PIXEL_ENC_YUV, .mem_planes = 1, .comp_planes = 3, .bpp = { 1, 1, 1, 0 }, .bpp_div = { 1, 1, 1, 1 }, .hdiv = 4, .vdiv = 4 },
 		{ .format = V4L2_PIX_FMT_YVU410,  .pixel_enc = V4L2_PIXEL_ENC_YUV, .mem_planes = 1, .comp_planes = 3, .bpp = { 1, 1, 1, 0 }, .bpp_div = { 1, 1, 1, 1 }, .hdiv = 4, .vdiv = 4 },
drivers/media/v4l2-core/v4l2-ioctl.c +1 -0
index b7d248ab7db2..f2655c5ea54c 100644
@@ -1369,6 +1369,7 @@ static void v4l_fill_fmtdesc(struct v4l2_fmtdesc *fmt)
 	case V4L2_PIX_FMT_NV42:		descr = "Y/VU 4:4:4"; break;
 	case V4L2_PIX_FMT_P010:		descr = "10-bit Y/UV 4:2:0"; break;
 	case V4L2_PIX_FMT_P012:		descr = "12-bit Y/UV 4:2:0"; break;
+	case V4L2_PIX_FMT_P210:		descr = "10-bit Y/UV 4:2:2"; break;
 	case V4L2_PIX_FMT_NV12_4L4:	descr = "Y/UV 4:2:0 (4x4 Linear)"; break;
 	case V4L2_PIX_FMT_NV12_16L16:	descr = "Y/UV 4:2:0 (16x16 Linear)"; break;
 	case V4L2_PIX_FMT_NV12_32L32:   descr = "Y/UV 4:2:0 (32x32 Linear)"; break;
include/uapi/linux/videodev2.h +1 -0
index 5373dba640fa..5472e433ed06 100644
@@ -659,6 +659,7 @@ struct v4l2_pix_format {
 #define V4L2_PIX_FMT_NV42    v4l2_fourcc('N', 'V', '4', '2') /* 24  Y/CrCb 4:4:4  */
 #define V4L2_PIX_FMT_P010    v4l2_fourcc('P', '0', '1', '0') /* 24  Y/CbCr 4:2:0 10-bit per component */
 #define V4L2_PIX_FMT_P012    v4l2_fourcc('P', '0', '1', '2') /* 24  Y/CbCr 4:2:0 12-bit per component */
+#define V4L2_PIX_FMT_P210    v4l2_fourcc('P', '2', '1', '0') /* 32  Y/CbCr 4:2:2 10-bit per component */
 
 /* two non contiguous planes - one Y, one Cr + Cb interleaved  */
 #define V4L2_PIX_FMT_NV12M   v4l2_fourcc('N', 'M', '1', '2') /* 12  Y/CbCr 4:2:0  */
Signature · 1 line
2.56.0
#4 lore raw

PATCH v4 3/17 media: v4l2: Add Apple interchange pixel formats

In reply to Sofus Forstreuter

Apple Interchange is a compressed and tiled format modifier.

Its intended use is for sharing buffers between hardware blocks (GPU, display controller, video codecs) on Apple platforms.

Add it to the v4l2_format_info table to help with calculating sizes.

---
 .../userspace-api/media/v4l/pixfmt-reserved.rst    | 30 ++++++++++++++++++++++
 drivers/media/v4l2-core/v4l2-common.c              |  7 +++++
 drivers/media/v4l2-core/v4l2-ioctl.c               |  6 +++++
 include/uapi/linux/videodev2.h                     |  8 ++++++
 4 files changed, 51 insertions(+)
Documentation/userspace-api/media/v4l/pixfmt-reserved.rst +30 -0
index 1cf6c59f4bc4..54995ea35a0e 100644
@@ -283,6 +283,36 @@ please make a proposal on the linux-media mailing list.
       - Compressed format used by Nuvoton NPCM video driver. This format is
         defined in Remote Framebuffer Protocol (RFC 6143, chapter 7.7.4 Hextile
         Encoding).
+    * .. _V4L2-PIX-FMT-APPLE-AX12:
+
+      - ``V4L2_PIX_FMT_APPLE_AX12``
+      - 'AX12'
+      - Apple Interchange NV12
+    * .. _V4L2-PIX-FMT-APPLE-AX16:
+
+      - ``V4L2_PIX_FMT_APPLE_AX16``
+      - 'AX16'
+      - Apple Interchange NV16
+    * .. _V4L2-PIX-FMT-APPLE-AX24:
+
+      - ``V4L2_PIX_FMT_APPLE_AX24``
+      - 'AX24'
+      - Apple Interchange NV24
+    * .. _V4L2-PIX-FMT-APPLE-AX03:
+
+      - ``V4L2_PIX_FMT_APPLE_AX03``
+      - 'AX03'
+      - Apple Interchange P030
+    * .. _V4L2-PIX-FMT-APPLE-AX23:
+
+      - ``V4L2_PIX_FMT_APPLE_AX23``
+      - 'AX23'
+      - Apple Interchange P230
+    * .. _V4L2-PIX-FMT-APPLE-AX43:
+
+      - ``V4L2_PIX_FMT_APPLE_AX43``
+      - 'AX43'
+      - Apple Interchange P430
 .. raw:: latex
 
     \normalsize
drivers/media/v4l2-core/v4l2-common.c +7 -0
index 43ef12d073a3..e57819a7fb40 100644
@@ -336,6 +336,13 @@ const struct v4l2_format_info *v4l2_format_info(u32 format)
 		{ .format = V4L2_PIX_FMT_GREY,    .pixel_enc = V4L2_PIXEL_ENC_YUV, .mem_planes = 1, .comp_planes = 1, .bpp = { 1, 0, 0, 0 }, .bpp_div = { 1, 1, 1, 1 }, .hdiv = 1, .vdiv = 1 },
 		{ .format = V4L2_PIX_FMT_Y12,     .pixel_enc = V4L2_PIXEL_ENC_YUV, .mem_planes = 1, .comp_planes = 1, .bpp = { 2, 0, 0, 0 }, .bpp_div = { 1, 1, 1, 1 }, .hdiv = 1, .vdiv = 1 },
 
+		{ .format = V4L2_PIX_FMT_APPLE_AX12, .pixel_enc = V4L2_PIXEL_ENC_YUV, .mem_planes = 1, .comp_planes = 2, .bpp = { 1, 2, 0, 0 }, .bpp_div = { 1, 1, 1, 1 }, .hdiv = 2, .vdiv = 2 },
+		{ .format = V4L2_PIX_FMT_APPLE_AX16, .pixel_enc = V4L2_PIXEL_ENC_YUV, .mem_planes = 1, .comp_planes = 2, .bpp = { 1, 2, 0, 0 }, .bpp_div = { 1, 1, 1, 1 }, .hdiv = 2, .vdiv = 1 },
+		{ .format = V4L2_PIX_FMT_APPLE_AX24, .pixel_enc = V4L2_PIXEL_ENC_YUV, .mem_planes = 1, .comp_planes = 2, .bpp = { 1, 2, 0, 0 }, .bpp_div = { 1, 1, 1, 1 }, .hdiv = 1, .vdiv = 1 },
+		{ .format = V4L2_PIX_FMT_APPLE_AX03, .pixel_enc = V4L2_PIXEL_ENC_YUV, .mem_planes = 1, .comp_planes = 2, .bpp = { 4, 8, 0, 0 }, .bpp_div = { 3, 3, 1, 1 }, .hdiv = 2, .vdiv = 2 },
+		{ .format = V4L2_PIX_FMT_APPLE_AX23, .pixel_enc = V4L2_PIXEL_ENC_YUV, .mem_planes = 1, .comp_planes = 2, .bpp = { 4, 8, 0, 0 }, .bpp_div = { 3, 3, 1, 1 }, .hdiv = 2, .vdiv = 1 },
+		{ .format = V4L2_PIX_FMT_APPLE_AX43, .pixel_enc = V4L2_PIXEL_ENC_YUV, .mem_planes = 1, .comp_planes = 2, .bpp = { 4, 8, 0, 0 }, .bpp_div = { 3, 3, 1, 1 }, .hdiv = 1, .vdiv = 1 },
+
 		/* Tiled YUV formats */
 		{ .format = V4L2_PIX_FMT_NV12_4L4, .pixel_enc = V4L2_PIXEL_ENC_YUV, .mem_planes = 1, .comp_planes = 2, .bpp = { 1, 2, 0, 0 }, .bpp_div = { 1, 1, 1, 1 }, .hdiv = 2, .vdiv = 2 },
 		{ .format = V4L2_PIX_FMT_NV15_4L4, .pixel_enc = V4L2_PIXEL_ENC_YUV, .mem_planes = 1, .comp_planes = 2, .bpp = { 5, 10, 0, 0 }, .bpp_div = { 4, 4, 1, 1 }, .hdiv = 2, .vdiv = 2,
drivers/media/v4l2-core/v4l2-ioctl.c +6 -0
index f2655c5ea54c..bbf81a89e2c5 100644
@@ -1561,6 +1561,12 @@ static void v4l_fill_fmtdesc(struct v4l2_fmtdesc *fmt)
 		case V4L2_PIX_FMT_PISP_COMP2_GBRG: descr = "PiSP 8b GBGB/RGRG mode2 compr"; break;
 		case V4L2_PIX_FMT_PISP_COMP2_BGGR: descr = "PiSP 8b BGBG/GRGR mode2 compr"; break;
 		case V4L2_PIX_FMT_PISP_COMP2_MONO: descr = "PiSP 8b monochrome mode2 compr"; break;
+		case V4L2_PIX_FMT_APPLE_AX12:	descr = "Apple Interchange NV12"; break;
+		case V4L2_PIX_FMT_APPLE_AX16:	descr = "Apple Interchange NV16"; break;
+		case V4L2_PIX_FMT_APPLE_AX24:	descr = "Apple Interchange NV24"; break;
+		case V4L2_PIX_FMT_APPLE_AX03:	descr = "Apple Interchange P030"; break;
+		case V4L2_PIX_FMT_APPLE_AX23:	descr = "Apple Interchange P230"; break;
+		case V4L2_PIX_FMT_APPLE_AX43:	descr = "Apple Interchange P430"; break;
 		default:
 			if (fmt->description[0])
 				return;
include/uapi/linux/videodev2.h +8 -0
index 5472e433ed06..f218f4fb26a4 100644
@@ -842,6 +842,14 @@ struct v4l2_pix_format {
 #define V4L2_PIX_FMT_PISP_COMP2_BGGR	v4l2_fourcc('P', 'C', '2', 'B') /* PiSP 8-bit mode 2 compressed BGGR bayer */
 #define V4L2_PIX_FMT_PISP_COMP2_MONO	v4l2_fourcc('P', 'C', '2', 'M') /* PiSP 8-bit mode 2 compressed monochrome */
 
+/* Apple Interchange, compressed and tiled formats */
+#define V4L2_PIX_FMT_APPLE_AX12	v4l2_fourcc('A', 'X', '1', '2') /* Apple Interchange NV12 */
+#define V4L2_PIX_FMT_APPLE_AX16	v4l2_fourcc('A', 'X', '1', '6') /* Apple Interchange NV16 */
+#define V4L2_PIX_FMT_APPLE_AX24	v4l2_fourcc('A', 'X', '2', '4') /* Apple Interchange NV24 */
+#define V4L2_PIX_FMT_APPLE_AX03	v4l2_fourcc('A', 'X', '0', '3') /* Apple Interchange P030 */
+#define V4L2_PIX_FMT_APPLE_AX23	v4l2_fourcc('A', 'X', '2', '3') /* Apple Interchange P230 */
+#define V4L2_PIX_FMT_APPLE_AX43	v4l2_fourcc('A', 'X', '4', '3') /* Apple Interchange P430 */
+
 /* Renesas RZ/V2H CRU packed formats. 64-bit units with contiguous pixels */
 #define V4L2_PIX_FMT_RAW_CRU10	v4l2_fourcc('C', 'R', '1', '0')
 #define V4L2_PIX_FMT_RAW_CRU12	v4l2_fourcc('C', 'R', '1', '2')
Signature · 1 line
2.56.0
#5 lore raw

PATCH v4 4/17 media: v4l2-ctrls: validate AV1 context_update_tile_id

In reply to Sofus Forstreuter

Increase V4L2_AV1_MAX_TILE_COUNT to MAX_TILE_COLS * MAX_TILE_ROWS

---
Cc: Daniel Almeida <[email protected]>
Cc: Xiaoyong Lu <[email protected]>

---
 drivers/media/v4l2-core/v4l2-ctrls-core.c | 9 +++++++++
 include/uapi/linux/v4l2-controls.h        | 2 +-
 2 files changed, 10 insertions(+), 1 deletion(-)
drivers/media/v4l2-core/v4l2-ctrls-core.c +9 -0
index 12a799824c44..6ded78ef7b0f 100644
@@ -114,6 +114,7 @@ static void std_init_compound(const struct v4l2_ctrl *ctrl, u32 idx,
 	struct v4l2_ctrl_vp9_frame *p_vp9_frame;
 	struct v4l2_ctrl_fwht_params *p_fwht_params;
 	struct v4l2_ctrl_h264_scaling_matrix *p_h264_scaling_matrix;
+	struct v4l2_ctrl_av1_frame *p_av1_frame;
 	struct v4l2_ctrl_av1_sequence *p_av1_sequence;
 	struct v4l2_ctrl_hevc_sps *p_hevc_sps;
 	void *p = ptr.p + idx * ctrl->elem_size;
@@ -162,6 +163,11 @@ static void std_init_compound(const struct v4l2_ctrl *ctrl, u32 idx,
 		p_vp9_frame->flags |= V4L2_VP9_FRAME_FLAG_X_SUBSAMPLING |
 			V4L2_VP9_FRAME_FLAG_Y_SUBSAMPLING;
 		break;
+	case V4L2_CTRL_TYPE_AV1_FRAME:
+		p_av1_frame = p;
+		p_av1_frame->tile_info.tile_cols = 1;
+		p_av1_frame->tile_info.tile_rows = 1;
+		break;
 	case V4L2_CTRL_TYPE_AV1_SEQUENCE:
 		p_av1_sequence = p;
 		/*
@@ -814,6 +820,9 @@ static int validate_av1_tile_info(struct v4l2_av1_tile_info *t)
 	if ((u32)t->tile_cols * t->tile_rows > V4L2_AV1_MAX_TILE_COUNT)
 		return -EINVAL;
 
+	if (t->context_update_tile_id >= t->tile_cols * t->tile_rows)
+		return -EINVAL;
+
 	return 0;
 }
 
include/uapi/linux/v4l2-controls.h +1 -1
index d17e41d51d2e..abdfa102a77b 100644
@@ -2939,7 +2939,7 @@ struct v4l2_ctrl_vp9_compressed_hdr {
 #define V4L2_AV1_MAX_NUM_PLANES		3
 #define V4L2_AV1_MAX_TILE_COLS		64
 #define V4L2_AV1_MAX_TILE_ROWS		64
-#define V4L2_AV1_MAX_TILE_COUNT		512
+#define V4L2_AV1_MAX_TILE_COUNT		4096
 
 #define V4L2_AV1_SEQUENCE_FLAG_STILL_PICTURE		  0x00000001
 #define V4L2_AV1_SEQUENCE_FLAG_USE_128X128_SUPERBLOCK	  0x00000002
Signature · 1 line
2.56.0
#6 lore raw

Re: [PATCH v4 04/17] media: v4l2-ctrls: validate AV1 context_update_tile_id

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [Medium] media: v4l2-ctrls: V4L2_AV1_MAX_TILE_COUNT increase inflates mtk buffers 8x - [Low] media…

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [Medium] media: v4l2-ctrls: V4L2_AV1_MAX_TILE_COUNT increase inflates mtk buffers 8x
- [Low] media: v4l2-ctrls: incomplete changelog for AV1 tile init and max tile count
--

commit aa08fd69f876d8214a79152486ea6debf2235ddc
Author: Sofus Forstreuter <[email protected]>

Quoted 6 lines

media: v4l2-ctrls: validate AV1 context_update_tile_id

Increase V4L2_AV1_MAX_TILE_COUNT to MAX_TILE_COLS * MAX_TILE_ROWS

[Severity: Low]
This isn't a bug, but the commit message does not explain why context_update_tile_id is checked against tile_cols * tile_rows in validate_av1_tile_info(), fails to mention initializing default tile_cols and tile_rows to 1 in std_init_compound() so default controls pass that check, and does not explain why V4L2_AV1_MAX_TILE_COUNT is increased in the same commit.

include/uapi/linux/v4l2-controls.h struct v4l2_ctrl_vp9_compressed_hdr { · line 2942

Quoted 10 lines
include/uapi/linux/v4l2-controls.h +1 -1
index d17e41d51d2ec..abdfa102a77bb 100644
@@ -2939,7 +2939,7 @@ struct v4l2_ctrl_vp9_compressed_hdr {
 #define V4L2_AV1_MAX_NUM_PLANES		3
 #define V4L2_AV1_MAX_TILE_COLS		64
 #define V4L2_AV1_MAX_TILE_ROWS		64
-#define V4L2_AV1_MAX_TILE_COUNT		512
+#define V4L2_AV1_MAX_TILE_COUNT		4096

[Severity: Medium]
Should V4L2_AV1_MAX_TILE_COUNT be raised to 4096?

With tile_cols and tile_rows already capped at 64 in validate_av1_tile_info(), setting V4L2_AV1_MAX_TILE_COUNT to 64 * 64 turns the (u32)t->tile_cols * t->tile_rows > V4L2_AV1_MAX_TILE_COUNT check into dead code, while context_update_tile_id is a __u8 that cannot address tile IDs >= 256.

In the MediaTek AV1 decoder, struct vdec_av1_slice_tile_group embeds two u32[V4L2_AV1_MAX_TILE_COUNT] arrays inside struct vdec_av1_slice_instance, so this 8x increase grows the kzalloc_obj(*instance) allocation in vdec_av1_slice_init() from ~5.1 KB to ~33.8 KB (a costly order-4 physically contiguous allocation) and increases per-context coherent DMA tile buffers in vdec_av1_slice_alloc_working_buffer() and vdec_msg_queue_init() from 128 KB to 1 MB.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=4
#7 lore raw

PATCH v4 5/17 media: v4l2-ctrls: validate vp9 tile_rows_log2

In reply to Sofus Forstreuter

tile_rows_log2 does not have a maximum specified in the spec, but it can be derived from 6.2.13 Tile info syntax:

tile_rows_log2 = f(1)
if (tile_rows_log2 == 1)
tile_rows_log2 += f(1)

---
 drivers/media/v4l2-core/v4l2-ctrls-core.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/media/v4l2-core/v4l2-ctrls-core.c +1 -1
index 6ded78ef7b0f..5261028767ef 100644
@@ -644,7 +644,7 @@ validate_vp9_frame(struct v4l2_ctrl_vp9_frame *frame)
 	 * According to the spec, tile_cols_log2 shall be less than or equal
 	 * to 6.
 	 */
-	if (frame->tile_cols_log2 > 6)
+	if (frame->tile_cols_log2 > 6 || frame->tile_rows_log2 > 2)
 		return -EINVAL;
 
 	if (frame->reference_mode > V4L2_VP9_REFERENCE_MODE_SELECT)
Signature · 1 line
2.56.0
#8 lore raw

Re: [PATCH v4 05/17] media: v4l2-ctrls: validate vp9 tile_rows_log2

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Low] media: v4l2-ctrls: missing Fixes trailer for validate_vp9_frame() --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Low] media: v4l2-ctrls: missing Fixes trailer for validate_vp9_frame()
--

commit 1ada1444fbd597671a6e73085c4ffdc493411791
Author: Sofus Forstreuter <[email protected]>

Quoted 11 lines

media: v4l2-ctrls: validate vp9 tile_rows_log2

tile_rows_log2 does not have a maximum specified in the spec, but it can be derived from 6.2.13 Tile info syntax:

tile_rows_log2 = f(1)
if (tile_rows_log2 == 1)
tile_rows_log2 += f(1)

[Severity: Low]
Since validate_vp9_frame() omitted the upper-bound check on frame->tile_rows_log2 when VP9 stateless decoder controls were added, should this include a Fixes tag for stable backporting?

Fixes b88dbe38dca8 ("media: uapi: Add VP9 stateless decoder controls")
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=5
#9 lore raw

PATCH v4 6/17 media: apple: add avd driver

In reply to Sofus Forstreuter

Add the AVD (Apple Video Decoder) driver with V4L2 M2M stateless support based largely on rockchips implementation.

---
 MAINTAINERS                                 |   1 +
 drivers/media/platform/Kconfig              |   1 +
 drivers/media/platform/Makefile             |   1 +
 drivers/media/platform/apple/Kconfig        |   5 +
 drivers/media/platform/apple/Makefile       |   3 +
 drivers/media/platform/apple/avd/Kconfig    |  18 +
 drivers/media/platform/apple/avd/Makefile   |   4 +
 drivers/media/platform/apple/avd/avd-drv.c  | 881 ++++++++++++++++++++++++++++
 drivers/media/platform/apple/avd/avd-inst.h | 215 +++++++
 drivers/media/platform/apple/avd/avd-v4l2.c | 819 ++++++++++++++++++++++++++
 drivers/media/platform/apple/avd/avd.h      | 248 ++++++++
 11 files changed, 2196 insertions(+)
MAINTAINERS +1 -0
index 5dd197078130..9be8111d013d 100644
@@ -2769,6 +2769,7 @@ F:	drivers/input/touchscreen/apple_z2.c
 F:	drivers/iommu/apple-dart.c
 F:	drivers/iommu/io-pgtable-dart.c
 F:	drivers/irqchip/irq-apple-aic.c
+F:	drivers/media/platform/apple/*
 F:	drivers/mfd/macsmc.c
 F:	drivers/nvme/host/apple.c
 F:	drivers/nvmem/apple-efuses.c
drivers/media/platform/Kconfig +1 -0
index 2c7699b6610b..280a9db25935 100644
@@ -66,6 +66,7 @@ source "drivers/media/platform/allegro-dvt/Kconfig"
 source "drivers/media/platform/amd/Kconfig"
 source "drivers/media/platform/amlogic/Kconfig"
 source "drivers/media/platform/amphion/Kconfig"
+source "drivers/media/platform/apple/Kconfig"
 source "drivers/media/platform/arm/Kconfig"
 source "drivers/media/platform/aspeed/Kconfig"
 source "drivers/media/platform/atmel/Kconfig"
drivers/media/platform/Makefile +1 -0
index d47c47d817da..aa82e189936b 100644
@@ -9,6 +9,7 @@ obj-y += allegro-dvt/
 obj-y += amd/
 obj-y += amlogic/
 obj-y += amphion/
+obj-y += apple/
 obj-y += arm/
 obj-y += aspeed/
 obj-y += atmel/
drivers/media/platform/apple/Kconfig new file +5 -0
new file mode 100644
index 000000000000..43c0a56c36a8
@@ -0,0 +1,5 @@
+# SPDX-License-Identifier: GPL-2.0-only
+
+comment "Apple media platform drivers"
+
+source "drivers/media/platform/apple/avd/Kconfig"
drivers/media/platform/apple/Makefile new file +3 -0
new file mode 100644
index 000000000000..d502cab93970
@@ -0,0 +1,3 @@
+# SPDX-License-Identifier: GPL-2.0-only
+
+obj-y += avd/
drivers/media/platform/apple/avd/Kconfig new file +18 -0
new file mode 100644
index 000000000000..c9e4d65b3d70
@@ -0,0 +1,18 @@
+# SPDX-License-Identifier: GPL-2.0
+
+config VIDEO_APPLE_AVD
+	tristate "Apple Silicon Video Decoding driver"
+	depends on VIDEO_DEV
+	depends on MEDIA_CONTROLLER
+	depends on ARCH_APPLE || COMPILE_TEST
+	depends on OF_ADDRESS
+	depends on V4L_PLATFORM_DRIVERS
+	select V4L2_MEM2MEM_DEV
+	select VIDEOBUF2_DMA_SG
+	select V4L2_H264
+	select V4L2_VP9
+	help
+	  Support for hardware video decoding on Apple Silicon devices using
+	  the Apple Video Decoder (AVD).
+	  To compile this driver as a module, choose M here: the module will
+	  be called apple-avd.
drivers/media/platform/apple/avd/Makefile new file +4 -0
new file mode 100644
index 000000000000..b2f6736a790e
@@ -0,0 +1,4 @@
+# SPDX-License-Identifier: GPL-2.0-only
+
+apple-avd-y := avd-drv.o avd-v4l2.o
+obj-$(CONFIG_VIDEO_APPLE_AVD) += apple-avd.o
drivers/media/platform/apple/avd/avd-drv.c new file +881 -0

881 lines not on this page · raw message

drivers/media/platform/apple/avd/avd-inst.h new file +215 -0

215 lines not on this page · raw message

drivers/media/platform/apple/avd/avd-v4l2.c new file +819 -0

819 lines not on this page · raw message

drivers/media/platform/apple/avd/avd.h new file +248 -0

248 lines not on this page · raw message

Signature · 1 line
2.56.0
#10 lore raw
Thank you for your contribution! Sashiko AI review found 9 potential issues to consider: - [High] media: apple: avd: use-after-free of ctx and m2m_ctx in avd_release() - [High] media: apple: avd…

Thank you for your contribution! Sashiko AI review found 9 potential issues to consider:
- [High] media: apple: avd: use-after-free of ctx and m2m_ctx in avd_release()
- [High] media: apple: avd: race between avd_irq_handler() and avd_watchdog_func()
- [High] media: apple: avd: misaligned comp_start address in avd_buf_prepare()
- [Medium] media: apple: avd: format warnings and off-by-one fw size check in avd_probe()
- [Medium] media: apple: avd: unreachable reset code and 2s error stall in avd_irq_handler()
- [Medium] media: apple: avd: IRQ enabled and firmware booted before m2m_dev init in avd_probe()
- [Medium] media: apple: avd: runtime PM disabled before V4L2 cleanup in avd_remove()
- [Low] media: apple: avd: undocumented compatible strings in avd_of_match
- [Low] media: apple: avd: avd_init_job() zeroes peak DMA buffer size every frame
--

commit 2e74415a1028a1a51430630c565f2d1729f1407a
Author: Sofus Forstreuter <[email protected]>

media: apple: add avd driver

This commit adds a V4L2 M2M stateless video decoder driver for the Apple Video Decoder (AVD) on Apple Silicon SoCs.

Quoted 5 lines
drivers/media/platform/apple/avd/avd-drv.c new file +0 -0
new file mode 100644
index 0000000000000..8896fe3e0b44a

[ ... ]

Quoted 9 lines
drivers/media/platform/apple/avd/avd-drv.c new file +9 -0
+int avd_init_job(struct avd_ctx *ctx, enum avd_codec codec, size_t segments)
+{
+	int ret = 0;
+	struct avd_job *job = &ctx->job;
+
+	job->codec = codec;
+	job->dest = SRAM_SEG_DST;
+	job->num = 0;
+	job->num_submit = 0;

drivers/media/platform/apple/avd/avd-drv.c line 221

Quoted 10 lines
drivers/media/platform/apple/avd/avd-drv.c new file +10 -0
+	job->num_alloc = segments;
+	ret = avd_buf_alloc(ctx->dev, &job->buf,
+			    job->num_alloc * sizeof(*job->segments));
+	if (ret)
+		return ret;
+
+	job->segments = job->buf.cpu;
+	memset(job->buf.cpu, 0, job->buf.size);
+	return 0;
+}

[Severity: Low]
Does avd_init_job() need to zero the entire job->buf.size on every frame?

When a frame requests fewer segments than a previous frame, avd_buf_alloc() reuses the existing DMA buffer and keeps job->buf.size at the historical peak size. Zeroing only job->num_alloc * sizeof(*job->segments) would avoid clearing unused coherent DMA memory after a frame with a high slice or tile count.

[ ... ]

Quoted 43 lines
drivers/media/platform/apple/avd/avd-drv.c new file +43 -0
+static void avd_watchdog_func(struct work_struct *work)
+{
+	struct avd_dev *avd;
+	struct avd_ctx *ctx;
+	int ret;
+
+	ctx = container_of(to_delayed_work(work), struct avd_ctx,
+			   watchdog_work);
+	if (!ctx)
+		return;
+
+	avd = ctx->dev;
+
+	dev_err(avd->dev, "Frame processing timed out!");
+
+	writel(0, avd->mbox + AVD_REG_MBOX_IRQ_ENABLE);
+	ret = avd_reset(avd);
+	if (ret)
+		dev_err(avd->dev, "failed to reset: %d", ret);
+
+	avd_job_finish(ctx, VB2_BUF_STATE_ERROR);
+}
+
+static irqreturn_t avd_irq_handler(int irq, void *data)
+{
+	struct avd_dev *avd = data;
+	struct avd_ctx *ctx;
+	enum vb2_buffer_state state;
+	enum fw_msg_sts msg_sts;
+	u32 status;
+
+	status = readl(avd->mbox + AVD_REG_MBOX0_RETRIEVE);
+	writel(AVD_MBOX0_NOT_EMPTY, avd->mbox + AVD_REG_MBOX_IRQ_CLR);
+
+	msg_sts = FIELD_GET(FW_MSG_STS, status);
+	if (msg_sts == STS_OK) {
+		state = VB2_BUF_STATE_DONE;
+	} else if (msg_sts == STS_ERR_DEC) {
+		dev_err_ratelimited(avd->dev, "VP%02ld failed to decode",
+				    FIELD_GET(FW_MSG_VAL, status));
+		state = VB2_BUF_STATE_ERROR;
+
+		/*

drivers/media/platform/apple/avd/avd-drv.c line 360

Quoted 10 lines
drivers/media/platform/apple/avd/avd-drv.c new file +10 -0
+		 * Resetting now will cause an SError since nothing stops the
+		 * iommu from accessing the hw while its turned of.
+		 *
+		 * Only reset in the watchdog where there is a good chance
+		 * that nothing uses the iommu.
+		 */
+		return IRQ_HANDLED;
+		/* The watchdog can try again if we fail */
+		if (avd_reset(avd))
+			return IRQ_HANDLED;

[Severity: Medium]
The unconditional return IRQ_HANDLED in the STS_ERR_DEC branch leaves the avd_reset() check unreachable and state = VB2_BUF_STATE_ERROR unused. Because the handler returns without finishing the job or rescheduling ctx->watchdog_work to run sooner, every frame decode error stalls the M2M queue for the remainder of the 2000ms watchdog timeout.

Quoted 7 lines
drivers/media/platform/apple/avd/avd-drv.c new file +7 -0
+	} else {
+		dev_err(avd->dev, "Unhandled FW status: %d %#x",
+			msg_sts, status);
+		writel(0, avd->mbox + AVD_REG_MBOX_IRQ_ENABLE);
+		return IRQ_HANDLED;
+	}
+

drivers/media/platform/apple/avd/avd-drv.c line 377

Quoted 10 lines
drivers/media/platform/apple/avd/avd-drv.c new file +10 -0
+	ctx = v4l2_m2m_get_curr_priv(avd->m2m_dev);
+	if (WARN_ON(!ctx))
+		return IRQ_HANDLED;
+
+	/* if the watchdog_work has run the work has already been submitted */
+	if (cancel_delayed_work(&ctx->watchdog_work))
+		avd_job_finish(ctx, state);
+
+	return IRQ_HANDLED;
+}

[Severity: High]
What serializes the threaded avd_irq_handler() against avd_watchdog_func()?

Writing 0 to AVD_REG_MBOX_IRQ_ENABLE in avd_watchdog_func() does not wait for an already-running threaded IRQ handler, so avd_irq_handler() can touch avd->mbox while avd_reset() is resetting the hardware and cycling the IOMMU domain. Further, once the worker thread starts avd_watchdog_func(), the pending bit on ctx->watchdog_work is already clear:

kworker irq/mbox0
avd_watchdog_func()
avd_reset(avd)
avd_job_finish(ctx, ...)

    ...
    v4l2_m2m_schedule_next_job()
      avd_device_run()
        ...
        avd_submit_job()
          schedule_delayed_work(
            &ctx->watchdog_work)
                                  avd_irq_handler()
                                    ctx = v4l2_m2m_get_curr_priv(...)
                                    cancel_delayed_work(&ctx->watchdog_work)
                                      --> returns true (cancels job 2!)
                                    avd_job_finish(ctx, state)

The late IRQ from the first job cancels the newly armed watchdog for the second job and finishes the second job while DMA is still active. If instead no second job is queued and userspace is closing the fd in avd_release(), avd_job_finish() in avd_watchdog_func() unblocks v4l2_m2m_ctx_release() and frees ctx after avd_irq_handler() has already fetched ctx from v4l2_m2m_get_curr_priv(), leading to a use-after-free on cancel_delayed_work(&ctx->watchdog_work).

[ ... ]

Quoted 9 lines
drivers/media/platform/apple/avd/avd-drv.c new file +9 -0
+static int avd_release(struct file *filp)
+{
+	struct avd_ctx *ctx = file_to_ctx(filp);
+
+	/*
+	 * Wait for any m2m job completions. This will either cancel or
+	 * complete the watchdog
+	 */
+	v4l2_m2m_ctx_release(ctx->fh.m2m_ctx);

drivers/media/platform/apple/avd/avd-drv.c line 504

Quoted 10 lines
drivers/media/platform/apple/avd/avd-drv.c new file +10 -0
+	v4l2_ctrl_handler_free(&ctx->ctrl_hdl);
+	v4l2_fh_del(&ctx->fh, filp);
+	v4l2_fh_exit(&ctx->fh);
+	avd_buf_free(ctx->dev, &ctx->inst);
+	avd_buf_free(ctx->dev, &ctx->histogram);
+	avd_buf_free(ctx->dev, &ctx->job.buf);
+	kfree(ctx);
+
+	return 0;
+}

[Severity: High]
Can avd_release() free ctx->fh.m2m_ctx and ctx while avd_watchdog_func() or avd_irq_handler() is still finishing a job?

v4l2_m2m_ctx_release() calls v4l2_m2m_cancel_job(), which only waits until TRANS_RUNNING is cleared in _v4l2_m2m_job_finish(), and avd_release() never calls cancel_delayed_work_sync(&ctx->watchdog_work):

CPU0 kworker
avd_release() avd_watchdog_func()
v4l2_m2m_ctx_release(m2m_ctx) avd_job_finish(ctx, ...)

    v4l2_m2m_cancel_job()             ...
      wait_event(m2m_ctx->finished)   _v4l2_m2m_job_finish()
                                        m2m_ctx->job_flags &= ~TRANS_RUNNING
                                        wake_up(&m2m_ctx->finished)
    ...
    kfree(m2m_ctx)
                                      v4l2_m2m_schedule_next_job(..., m2m_ctx)
                                        <-- use-after-free of m2m_ctx

kfree(ctx) ...
<-- use-after-free of ctx

Closing the video device while a job times out or completes can therefore use m2m_ctx and ctx after they have been freed.

[ ... ]

drivers/media/platform/apple/avd/avd-drv.c line 694

Quoted 11 lines
drivers/media/platform/apple/avd/avd-drv.c new file +11 -0
+/* can also be derived from a version register */
+static const struct of_device_id avd_of_match[] = {
+	{ .compatible = "apple,t8103-avd", .data = &avd_t8103_variant },
+	{ .compatible = "apple,t6000-avd", .data = &avd_t6000_variant },
+	{ .compatible = "apple,t8112-avd", .data = &avd_t8112_variant },
+	{ .compatible = "apple,t6020-avd", .data = &avd_t6020_variant },
+	{ .compatible = "apple,t8122-avd", .data = &avd_t8122_variant },
+	{ .compatible = "apple,t8132-avd", .data = &avd_t8132_variant },
+	{ .compatible = "apple,t8140-avd", .data = &avd_t8140_variant },
+	{},
+};

[Severity: Low]
"apple,t8132-avd" and "apple,t8140-avd" are not documented in Documentation/devicetree/bindings/media/apple,avd.yaml, which triggers checkpatch.pl UNDOCUMENTED_DT_STRING warnings and dtbs_check failures.

[ ... ]

Quoted 10 lines
drivers/media/platform/apple/avd/avd-drv.c new file +10 -0
+	irq = platform_get_irq_byname(pdev, "mbox0");
+	if (irq < 0)
+		return irq;
+	ret = devm_request_threaded_irq(&pdev->dev, irq, NULL, avd_irq_handler,
+					IRQF_ONESHOT, dev_name(&pdev->dev),
+					avd);
+	if (ret) {
+		dev_err(avd->dev, "Could not request mbox0 IRQ");
+		return ret;
+	}

[ ... ]

drivers/media/platform/apple/avd/avd-drv.c line 786

Quoted 7 lines
drivers/media/platform/apple/avd/avd-drv.c new file +7 -0
+	res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "code");
+	if (avd->fw->size > res->end - res->start) {
+		dev_err(avd->dev, "Firmware is to large: %#lx max %#llx",
+			avd->fw->size, res->end - res->start);
+		ret = -EINVAL;
+		goto err_rel_fw;
+	}

[Severity: Medium]
Should this check use resource_size(res) instead of res->end - res->start?

struct resource uses inclusive bounds, so res->end - res->start is off by one byte. With COMPILE_TEST enabled in Kconfig, formatting size_t (avd->fw->size) with %#lx and resource_size_t with %#llx also causes -Wformat warnings on 32-bit builds (%#zx and %pa withresource_size() avoid that). In addition, nothing checks that avd->fw->size is a multiple of 4 before avd_boot() passes it to avd_memcpy_toio(), which triggers WARN_ON(len % 4) and truncates trailing bytes.

Quoted 14 lines
drivers/media/platform/apple/avd/avd-drv.c new file +14 -0
+
+	pm_runtime_set_autosuspend_delay(avd->dev, 100);
+	pm_runtime_use_autosuspend(avd->dev);
+	pm_runtime_enable(avd->dev);
+
+	ret = pm_runtime_resume_and_get(avd->dev);
+	if (ret < 0)
+		goto err_disable_runtime_pm;
+
+	if (avd->variant->revision > 3)
+		avd_version = readl_relaxed(avd->ctrl);
+	else
+		avd_version = 2 << 16;
+	piodma_version = readl_relaxed(avd->piodma + PIODMA_REG_HW_VERSION);

drivers/media/platform/apple/avd/avd-drv.c line 810

Quoted 10 lines
drivers/media/platform/apple/avd/avd-drv.c new file +10 -0
+
+	dev_info(avd->dev, "HW version: %d.%d PIODMA version: %d.%d",
+		 avd_version >> 16, avd_version & 0xffff,
+		 piodma_version >> 16, piodma_version & 0xffff);
+
+	pm_runtime_put(avd->dev);
+
+	ret = avd_v4l2_init(avd);
+	if (ret)
+		goto err_disable_runtime_pm;

[Severity: Medium]
Can an mbox0 interrupt fire during avd_probe() before avd->m2m_dev is initialized?

devm_request_threaded_irq() enables the IRQ line before pm_runtime_enable() and before avd_v4l2_init() calls v4l2_m2m_init(). When pm_runtime_resume_and_get() runs avd_runtime_resume() -> avd_boot(), it enables AVD_MBOX0_NOT_EMPTY in AVD_REG_MBOX_IRQ_ENABLE and starts the CM3 processor while avd->m2m_dev is still NULL. If an interrupt arrives before v4l2_m2m_init() completes, avd_irq_handler() passes NULL to v4l2_m2m_get_curr_priv(avd->m2m_dev), causing a NULL pointer dereference.

[ ... ]

drivers/media/platform/apple/avd/avd-drv.c line 835

Quoted 12 lines
drivers/media/platform/apple/avd/avd-drv.c new file +12 -0
+static void avd_remove(struct platform_device *pdev)
+{
+	struct avd_dev *avd = platform_get_drvdata(pdev);
+
+	pm_runtime_dont_use_autosuspend(avd->dev);
+	pm_runtime_disable(avd->dev);
+
+	avd_v4l2_cleanup(avd);
+
+	release_firmware(avd->fw);
+	iommu_domain_free(avd->empty_domain);
+}

[Severity: Medium]
Should avd_v4l2_cleanup(avd) be called before disabling runtime PM in avd_remove()?

Disabling runtime PM while the video and media devices are still registered allows concurrent V4L2 operations or in-flight jobs to call runtime PM helpers after runtime PM is disabled, and does not mirror the reverse order of avd_probe().

Quoted 15 lines
drivers/media/platform/apple/avd/avd-drv.c new file +15 -0
+
+static __maybe_unused int avd_runtime_resume(struct device *dev)
+{
+	int ret;
+	struct avd_dev *avd = platform_get_drvdata(to_platform_device(dev));
+
+	ret = avd_boot(avd);
+	if (ret)
+		dev_err(dev, "failed to boot");
+	return ret;
+}
+
+static __maybe_unused int avd_runtime_suspend(struct device *dev)
+{
+	struct avd_dev *avd = platform_get_drvdata(to_platform_device(dev));

drivers/media/platform/apple/avd/avd-drv.c line 860

Quoted 10 lines
drivers/media/platform/apple/avd/avd-drv.c new file +10 -0
+
+	avd_shutdown(avd);
+	return 0;
+}
+
+static const struct dev_pm_ops avd_pm_ops = {
+	SET_SYSTEM_SLEEP_PM_OPS(pm_runtime_force_suspend,
+				pm_runtime_force_resume)
+	SET_RUNTIME_PM_OPS(avd_runtime_suspend, avd_runtime_resume, NULL)
+};

[Severity: Medium]
When CONFIG_PM is disabled (for example under COMPILE_TEST), SET_RUNTIME_PM_OPS drops avd_runtime_suspend(), leaving avd_shutdown() unreferenced and causing a -Wunused-function warning. Using SYSTEM_SLEEP_PM_OPS() and RUNTIME_PM_OPS() (and removing __maybe_unused) lets the compiler dead-code eliminate avd_shutdown() cleanly alongside pm_ptr(&avd_pm_ops).

Quoted 5 lines
drivers/media/platform/apple/avd/avd-v4l2.c new file +0 -0
new file mode 100644
index 0000000000000..5b085fb047d84

[ ... ]

Quoted 26 lines
drivers/media/platform/apple/avd/avd-v4l2.c new file +26 -0
+static void avd_fill_decoded_pixfmt(struct avd_ctx *ctx,
+				    struct v4l2_pix_format_mplane *pix_mp)
+{
+	struct avd_comp comp = {};
+	u32 sizeimage = 0;
+
+	v4l2_fill_pixfmt_mp(pix_mp, pix_mp->pixelformat, pix_mp->width,
+			    pix_mp->height);
+	sizeimage = pix_mp->plane_fmt[0].sizeimage;
+
+	if (is_interchange(pix_mp->pixelformat))
+		sizeimage = 0;
+	else
+		sizeimage = ALIGN(sizeimage, AVD_ALIGN);
+
+	fill_comp(&comp, ctx->image_fmt, pix_mp->width, pix_mp->height);
+	sizeimage += ALIGN(comp.size, AVD_ALIGN);
+
+	if (ctx->coded_fmt_desc->ops->aux_buf_size)
+		sizeimage +=
+			ALIGN(ctx->coded_fmt_desc->ops->aux_buf_size(ctx,
+								     pix_mp),
+			      AVD_ALIGN);
+
+	pix_mp->plane_fmt[0].sizeimage = sizeimage;
+}

[ ... ]

Quoted 2 lines
drivers/media/platform/apple/avd/avd-v4l2.c new file +2 -0
+static int avd_buf_prepare(struct vb2_buffer *vb)
+{

[ ... ]

drivers/media/platform/apple/avd/avd-v4l2.c line 618

Quoted 12 lines
drivers/media/platform/apple/avd/avd-v4l2.c new file +12 -0
+		if (!is_interchange(f->fmt.pix_mp.pixelformat)) {
+			size_t aux_size = 0;
+
+			if (ctx->coded_fmt_desc->ops->aux_buf_size)
+				aux_size =
+					ALIGN(ctx->coded_fmt_desc->ops->aux_buf_size(ctx, &f->fmt.pix_mp),
+					      AVD_ALIGN);
+
+			buf->dma.comp_start +=
+				ALIGN(f->fmt.pix_mp.plane_fmt[0].sizeimage,
+				      AVD_ALIGN) - (buf->comp.size + aux_size);
+		}

[Severity: High]
Does subtracting unaligned buf->comp.size here misalign buf->dma.comp_start?

avd_fill_decoded_pixfmt() reserves ALIGN(comp.size, AVD_ALIGN) bytes for the compressed section, whereas calc_tile_meta() only aligns the individual tile and metadata components in comp.size to 16 bytes (for example, at 128x128 8-bit 4:2:0, comp.size is 0x6280, which is not 256-byte aligned). Subtracting unaligned buf->comp.size instead of ALIGN(buf->comp.size, AVD_ALIGN) leaves buf->dma.comp_start misaligned; on IAS36 variants, push_comp_ias36() right-shifts (dec->dma.comp_start + dec->comp.offsets[i]) by 7, truncating the lower 7 bits and shifting the compressed buffer DMA writes into the preceding decompressed UV plane.

Also, in avd-drv.c, v4l2_format_info_bpp() computes:

8 * info->bpp[plane] / info->bpp_div[plane]

For plane 1 of 10-bit V4L2_PIX_FMT_APPLE_AX03 and V4L2_PIX_FMT_APPLE_AX23 (bpp[1] = 8, bpp_div[1] = 3), integer division yields 8 * 8 / 3 = 21 bits per UV pixel instead of 20, inflating the UV tile size in calc_tile_meta() from 640 bytes to 672 bytes.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=6
#11 lore raw

PATCH v4 7/17 media: apple: avd: add h264 support

In reply to Sofus Forstreuter

The fluster score is 77/135 for JVT-AVC_V1 and 42/69 for JVT-FR-EXT.

While there are no unexpected test cases. FM1_FT_E, SP1_BT_A and sp2_bt_b still have some unsupported features that are not rejected, which causes the hardware to fault.

---
 drivers/media/platform/apple/avd/Kconfig    |   1 -
 drivers/media/platform/apple/avd/Makefile   |   2 +-
 drivers/media/platform/apple/avd/avd-h264.c | 849 ++++++++++++++++++++++++++++
 drivers/media/platform/apple/avd/avd-v4l2.c |  72 ++-
 drivers/media/platform/apple/avd/avd.h      |   2 +
 5 files changed, 923 insertions(+), 3 deletions(-)
drivers/media/platform/apple/avd/Kconfig +0 -1
index c9e4d65b3d70..8775e82150d0 100644
@@ -10,7 +10,6 @@ config VIDEO_APPLE_AVD
 	select V4L2_MEM2MEM_DEV
 	select VIDEOBUF2_DMA_SG
 	select V4L2_H264
-	select V4L2_VP9
 	help
 	  Support for hardware video decoding on Apple Silicon devices using
 	  the Apple Video Decoder (AVD).
drivers/media/platform/apple/avd/Makefile +1 -1
index b2f6736a790e..482d43f8ea8e 100644
@@ -1,4 +1,4 @@
 # SPDX-License-Identifier: GPL-2.0-only
 
-apple-avd-y := avd-drv.o avd-v4l2.o
+apple-avd-y := avd-drv.o avd-v4l2.o avd-h264.o
 obj-$(CONFIG_VIDEO_APPLE_AVD) += apple-avd.o
drivers/media/platform/apple/avd/avd-h264.c new file +849 -0

849 lines not on this page · raw message

drivers/media/platform/apple/avd/avd-v4l2.c +71 -1

78 lines not on this page · raw message

drivers/media/platform/apple/avd/avd.h +2 -0
index 10777e551f15..f27a6de7126c 100644
@@ -223,6 +223,8 @@ void avd_job_finish(struct avd_ctx *ctx, enum vb2_buffer_state result);
 void avd_run_preamble(struct avd_ctx *ctx, struct avd_run *run);
 void avd_run_postamble(struct avd_ctx *ctx, struct avd_run *run);
 
+extern const struct avd_coded_fmt_ops avd_h264_fmt_ops;
+
 extern const struct v4l2_ctrl_ops avd_ctrl_ops;
 extern const struct v4l2_ioctl_ops avd_ioctl_ops;
 extern const struct vb2_ops avd_queue_ops;
Signature · 1 line
2.56.0
#12 lore raw

Re: [PATCH v4 07/17] media: apple: avd: add h264 support

Thank you for your contribution! Sashiko AI review found 12 potential issues to consider: - [High] media: apple: avd: missing SPS bounds checks in avd_h264_validate_sps() - [High] media: apple: avd…

Thank you for your contribution! Sashiko AI review found 12 potential issues to consider:
- [High] media: apple: avd: missing SPS bounds checks in avd_h264_validate_sps()
- [High] media: apple: avd: stale ctx->job.segments left by avd_h264_stop()
- [Medium] media: apple: avd: DPB active vs valid flag and index mismatch in stream_refs()
- [Medium] media: apple: avd: slice state not reset on error or new frame in avd_h264_run()
- [Medium] media: apple: avd: header_bit_size overflow and silent return in stream_slice()
- [Medium] media: apple: avd: off-by-one emulation byte scan in stream_slice()
- [Medium] media: apple: avd: implicit B-slice weights enabled on P slices in stream_weights()
- [Medium] media: apple: avd: race between avd_submit_job() IRQ and avd_run_postamble()
- [Medium] media: apple: avd: per-slice coherent DMA alloc/free churn and uncached scan
- [Low] media: apple: avd: uncommitted ctrl->p_new read in avd_h264_start()
- [Low] media: apple: avd: stale job->num_alloc in avd_h264_realloc_slices()
- [Low] media: apple: avd: unused reference lists built per slice in avd_h264_run()
--

commit 96734a8ed59f9431c4f708b792e9ab433ee539a0
Author: Sofus Forstreuter <[email protected]>

media: apple: avd: add h264 support

This commit adds V4L2 stateless H.264 slice-based decoding support to the Apple Video Decoder (AVD) driver.

Quoted 6 lines
drivers/media/platform/apple/avd/avd-h264.c new file +0 -0
new file mode 100644
index 0000000000000..cfa32d551b9df
@@ -0,0 +1,849 @@

[ ... ]

Quoted 25 lines
drivers/media/platform/apple/avd/avd-h264.c new file +25 -0
+static void stream_refs(struct avd_ctx *ctx, struct avd_h264_run *run)
+{
+	const struct v4l2_ctrl_h264_decode_params *decode = run->decode_params;
+	const struct v4l2_h264_dpb_entry *dpb = decode->dpb;
+	struct avd_h264_ctx *h264_ctx = ctx->priv;
+	struct avd_decoded_buffer *dst, *ref;
+
+	dst = vb2_to_avd_decoded_buf(&run->base.bufs.dst->vb2_buf);
+
+	push(0, "");
+	pusha(h264_ctx->bufs.mv_above_info.addr, "mv_above_info", 7);
+	pusha(run->base.dst->dma.aux_start, "mv_color", 0);
+
+	push(0, "");
+	push(0, "");
+	push(0, "");
+	push(0, "");
+
+	for (int i = 0; i < ARRAY_SIZE(decode->dpb); i++) {
+		if (!(dpb[i].flags & V4L2_H264_DPB_ENTRY_FLAG_VALID))
+			continue;
+
+		ref = avd_get_ref_buf(ctx, &dst->base.vb, dpb[i].reference_ts);
+
+		push(AVD_REF_NUM(run->num_valid - 1) | AVD_REF_FLAG_CONST |

drivers/media/platform/apple/avd/avd-h264.c line 130

Quoted 10 lines
drivers/media/platform/apple/avd/avd-h264.c new file +10 -0
+			     AVD_REF_FLAG_LONG(
+				     dpb[i].flags &
+				     V4L2_H264_DPB_ENTRY_FLAG_LONG_TERM) |
+			     AVD_REF_DELTA_POC(run->cur_poc -
+					       dpb[i].top_field_order_cnt),
+		     "hdr_d0_ref_hdr");
+
+		push_comp(ctx, ref);
+	}
+}

[Severity: Medium]
Can stream_refs() push a different number of reference descriptors than AVD_REF_NUM(run->num_valid - 1) declares?

v4l2_h264_init_reflist_builder() sets reflist_builder.num_valid by counting entries with V4L2_H264_DPB_ENTRY_FLAG_ACTIVE set, whereas stream_refs() filters decode->dpb[] by V4L2_H264_DPB_ENTRY_FLAG_VALID. Whenever a DPB entry is valid for display reordering but no longer active for reference, stream_refs() pushes extra reference headers and desynchronizes the fixed header command stream. Also, if run->num_valid is 0 on a non-IDR picture, run->num_valid - 1 underflows the 4-bit AVD_REF_NUM field to 15.

In addition, stream_refs() compacts non-contiguous DPB slots as it pushes them, while stream_slice() passes raw sl->ref_pic_list0[i].index and sl->ref_pic_list1[i].index values to AVD_OP_REF_DBP_IDX(), which expects the sequential submission index from stream_refs() and selects the wrong reference frame whenever decode->dpb[] has holes.

[ ... ]

drivers/media/platform/apple/avd/avd-h264.c line 306

Quoted 11 lines
drivers/media/platform/apple/avd/avd-h264.c new file +11 -0
+static void stream_weights(struct avd_ctx *ctx, struct avd_h264_run *run)
+{
+	int luma_denom, chroma_denom;
+	struct v4l2_h264_weight_factors factors;
+	const struct v4l2_ctrl_h264_pred_weights *weights = run->pred_weights;
+	const struct v4l2_ctrl_h264_pps *pps = run->pps;
+	const struct v4l2_ctrl_h264_slice_params *sl = run->slice_params;
+
+	bool pred_weight_req = V4L2_H264_CTRL_PRED_WEIGHTS_REQUIRED(pps, sl);
+	bool default_weights = pps->weighted_bipred_idc == 2 &&
+			       !pred_weight_req;

[Severity: Medium]
Does default_weights enable implicit B-slice weights on P slices when pps->weighted_bipred_idc == 2 and V4L2_H264_PPS_FLAG_WEIGHTED_PRED is not set?

stream_slice() calls stream_weights() for both P and B slices, and weighted_bipred_idc only applies to B slices, so P slices in streams with weighted_bipred_idc == 2 and unweighted P prediction will be decoded with AVD_OP_WEIGHTS_HDR_FLAG1(1) and corrupted. Should default_weights also check sl->slice_type == V4L2_H264_SLICE_TYPE_B?

[ ... ]

Quoted 21 lines
drivers/media/platform/apple/avd/avd-h264.c new file +21 -0
+static void stream_slice(struct avd_ctx *ctx, struct avd_h264_run *run)
+{
+	const struct v4l2_ctrl_h264_decode_params *decode = run->decode_params;
+	const struct v4l2_ctrl_h264_pps *pps = run->pps;
+	const struct v4l2_ctrl_h264_sps *sps = run->sps;
+	const struct v4l2_ctrl_h264_slice_params *sl = run->slice_params;
+	struct avd_h264_ctx *h264_ctx = ctx->priv;
+	u32 payload_len = h264_ctx->active_slice->size;
+	bool en_mode = (pps->flags & V4L2_H264_PPS_FLAG_ENTROPY_CODING_MODE) ==
+		       0;
+	const u8 *data = h264_ctx->active_slice->cpu;
+	u32 min_off = (sl->header_bit_size + (en_mode ? 0 : 7)) / 8;
+	u32 off = 2;
+	u32 num_ref_idx_active, bytes_read = 2;
+	dma_addr_t coded_in;
+	struct avd_decoded_buffer *dst, *ref;
+
+	dst = run->base.dst;
+
+	if (off > payload_len || payload_len < min_off)
+		return;

drivers/media/platform/apple/avd/avd-h264.c line 412

Quoted 10 lines
drivers/media/platform/apple/avd/avd-h264.c new file +10 -0
+
+	/* include emulation byte in offset to slice header */
+	while (bytes_read < min_off && off < payload_len) {
+		if (data[off - 2] != 0x00 || data[off - 1] != 0x00 ||
+		    data[off] != 0x03)
+			bytes_read++;
+		off++;
+	}
+
+	coded_in = h264_ctx->active_slice->addr + off;

[Severity: Medium]
Can this loop stop on a 0x03 emulation prevention byte right at the slice header boundary?

The loop terminates as soon as bytes_read reaches min_off without checking data[off]. If the last two RBSP bytes of the slice header are 0x00, 0x00 and an emulation prevention byte 0x03 sits at data[off] before RBSP byte min_off, coded_in will point at that 0x03 byte instead of the start of slice data.

[ ... ]

Quoted 17 lines
drivers/media/platform/apple/avd/avd-h264.c new file +17 -0
+	push(AVD_OP_SL_REF | AVD_OP_SL_REF_FLAG_CABAC(sl->cabac_init_idc == 1) |
+		     AVD_OP_SL_REF_FLAG1(sl->cabac_init_idc == 2) |
+		     AVD_OP_SL_REF_FLAG2(
+			     !(sl->flags &
+			       V4L2_H264_SLICE_FLAG_DIRECT_SPATIAL_MV_PRED)) |
+		     AVD_OP_SL_REF_NUM_L0(sl->num_ref_idx_l0_active_minus1) |
+		     AVD_OP_SL_REF_NUM_L1(sl->num_ref_idx_l1_active_minus1) |
+		     AVD_OP_SL_REF_SLICE_P(sl->slice_type ==
+					   V4L2_H264_SLICE_TYPE_P) |
+		     AVD_OP_SL_REF_SLICE_I(sl->slice_type ==
+					   V4L2_H264_SLICE_TYPE_I) |
+		     AVD_OP_SL_REF_SLICE_B(sl->slice_type ==
+					   V4L2_H264_SLICE_TYPE_B)
+
+		     ,
+	     "slc_6e4_cmd_ref_type");
+

drivers/media/platform/apple/avd/avd-h264.c line 498

Quoted 10 lines
drivers/media/platform/apple/avd/avd-h264.c new file +10 -0
+	if (sl->slice_type == V4L2_H264_SLICE_TYPE_B &&
+	    sl->ref_pic_list1[0].index < ARRAY_SIZE(decode->dpb)) {
+		/* bidirectional reference of previous mv */
+		ref = avd_get_ref_buf(
+			ctx, &dst->base.vb,
+			decode->dpb[sl->ref_pic_list1[0].index].reference_ts);
+
+		pusha(ref->dma.aux_start, "slc_a78_sps_tile_addr2_lsb8", 0);
+	}
+}

[Severity: Medium]
What happens when stream_slice() returns early on off > payload_len || payload_len < min_off, or when a B-slice has sl->ref_pic_list1[0].index >= ARRAY_SIZE(decode->dpb)?

Because stream_slice() returns void, avd_h264_run() still calls avd_end_segment() and avd_submit_job(), submitting an empty segment to the hardware instead of failing the request. In CABAC mode, sl->header_bit_size + 7 can also overflow u32 when computing min_off, wrapping min_off to 0 and bypassing the length check. Finally, on a B-slice with sl->ref_pic_list1[0].index >= ARRAY_SIZE(decode->dpb), AVD_OP_SL_REF_SLICE_B(1) is emitted without the following aux_start address operand that the opcode requires, faulting or hanging the decoder.

[ ... ]

Quoted 5 lines
drivers/media/platform/apple/avd/avd-h264.c new file +5 -0
+static int avd_h264_validate_sps(struct avd_ctx *ctx,
+				 const struct v4l2_ctrl_h264_sps *sps)
+{
+	if (sps->chroma_format_idc > 2)
+		/* Only 4:0:0, 4:2:0 and 4:2:2 are supported */

drivers/media/platform/apple/avd/avd-h264.c line 563

Quoted 10 lines
drivers/media/platform/apple/avd/avd-h264.c new file +10 -0
+		return -EINVAL;
+	if (sps->bit_depth_luma_minus8 != sps->bit_depth_chroma_minus8)
+		/* Luma and chroma bit depth mismatch */
+		return -EINVAL;
+	if (!(sps->flags & V4L2_H264_SPS_FLAG_FRAME_MBS_ONLY))
+		/* no interlaced support */
+		return -EINVAL;
+
+	return 0;
+}

[Severity: High]
Can an SPS with dimensions larger than ctx->coded_fmt or an unsupported bit depth cause out-of-bounds DMA writes?

avd_h264_alloc_bufs() sizes the internal scratch DMA buffers from fmt_width(ctx) and 8-bit or 10-bit depth, and the capture buffers are sized from ctx->decoded_fmt. However, stream_hdr() programs the hardware with width = (sps->pic_width_in_mbs_minus1 + 1) * 16,
height = (sps->pic_height_in_map_units_minus1 + 1) * 16, and sps->bit_depth_luma_minus8 directly from V4L2_CID_STATELESS_H264_SPS. Without checking in avd_h264_validate_sps() that the SPS macroblock dimensions fit within fmt_width(ctx) and fmt_height(ctx) and that sps->bit_depth_luma_minus8 is 0 or 2, the hardware can DMA-write past the end of the scratch and capture buffers.

Quoted 14 lines
drivers/media/platform/apple/avd/avd-h264.c new file +14 -0
+
+static void avd_h264_stop(struct avd_ctx *ctx)
+{
+	struct avd_h264_ctx *h264_ctx = ctx->priv;
+	struct avd_dev *dev = ctx->dev;
+	int i;
+
+	if (!h264_ctx)
+		return;
+
+	avd_buf_free(dev, &h264_ctx->bufs.above_info);
+	avd_buf_free(dev, &h264_ctx->bufs.lf_above_info);
+	avd_buf_free(dev, &h264_ctx->bufs.lf_above);
+	avd_buf_free(dev, &h264_ctx->bufs.ip_above);

drivers/media/platform/apple/avd/avd-h264.c line 587

Quoted 10 lines
drivers/media/platform/apple/avd/avd-h264.c new file +10 -0
+	avd_buf_free(dev, &h264_ctx->bufs.mv_above_info);
+
+	for (i = 0; i < h264_ctx->slice_num; i++)
+		avd_buf_free(dev, &h264_ctx->slices[i]);
+
+	kfree(h264_ctx->slices);
+	kfree(h264_ctx);
+
+	ctx->priv = NULL;
+}

[Severity: High]
Does avd_h264_stop() leave ctx->job.segments and ctx->job.num populated after freeing the scratch and slice DMA buffers?

If userspace queues slice(s) with V4L2_BUF_FLAG_M2M_HOLD_CAPTURE_BUF, stops and restarts streaming, and then queues a slice with first_mb_in_slice != 0, avd_h264_run() skips avd_init_job() while ctx->job.segments is still non-NULL. It then appends segments past ctx->job.num_alloc (writing out of bounds of ctx->job.buf.cpu) and submits the pre-STREAMOFF segments containing the freed DMA addresses of the previous stream's scratch and slice buffers.

Quoted 14 lines
drivers/media/platform/apple/avd/avd-h264.c new file +14 -0
+
+static int avd_h264_start(struct avd_ctx *ctx)
+{
+	struct avd_h264_ctx *h264_ctx;
+	struct v4l2_ctrl *ctrl;
+	int ret;
+
+	ctrl = v4l2_ctrl_find(&ctx->ctrl_hdl, V4L2_CID_STATELESS_H264_SPS);
+	if (!ctrl)
+		return -EINVAL;
+
+	ret = avd_h264_validate_sps(ctx, ctrl->p_cur.p_h264_sps);
+	if (ret)
+		return ret;

drivers/media/platform/apple/avd/avd-h264.c line 611

Quoted 10 lines
drivers/media/platform/apple/avd/avd-h264.c new file +10 -0
+
+	h264_ctx = kzalloc_obj(*h264_ctx, GFP_KERNEL);
+	if (!h264_ctx)
+		return -ENOMEM;
+
+	ctx->priv = h264_ctx;
+
+	/* assume one slice per row */
+	h264_ctx->alloc_slice_num =
+		ctrl->p_new.p_h264_sps->pic_height_in_map_units_minus1 + 1;

[Severity: Low]
Should alloc_slice_num read ctrl->p_cur.p_h264_sps instead of ctrl->p_new.p_h264_sps to match the committed SPS validated right above? ctrl->p_new is the V4L2 control scratch buffer and can hold uncommitted values from VIDIOC_TRY_EXT_CTRLS or staged requests.

[ ... ]

Quoted 17 lines
drivers/media/platform/apple/avd/avd-h264.c new file +17 -0
+static int avd_h264_realloc_slices(struct avd_ctx *ctx)
+{
+	struct avd_h264_ctx *h264_ctx = ctx->priv;
+	struct avd_job *job = &ctx->job;
+	struct avd_buf tmp_buf = {};
+	size_t alloc_slice_num;
+	void *tmp;
+	int ret;
+
+	tmp = h264_ctx->slices;
+	alloc_slice_num = (h264_ctx->alloc_slice_num * 3) / 2 + 1;
+	h264_ctx->slices =
+		kzalloc_objs(*h264_ctx->slices, alloc_slice_num, GFP_KERNEL);
+	if (!h264_ctx->slices)
+		goto err_revert_slices;
+
+	/* we could already have the correct size */

drivers/media/platform/apple/avd/avd-h264.c line 681

Quoted 10 lines
drivers/media/platform/apple/avd/avd-h264.c new file +10 -0
+	if ((alloc_slice_num + 1) * sizeof(*job->segments) < job->buf.size)
+		goto commit_slices;
+
+	ret = avd_buf_alloc(ctx->dev, &tmp_buf,
+			    (alloc_slice_num + 1) * sizeof(*job->segments));
+	if (ret)
+		goto err_free_slices;
+
+	job->segments = tmp_buf.cpu;
+	job->num_alloc = (alloc_slice_num + 1);

[Severity: Low]
When the existing job->buf is large enough and this jumps to commit_slices, is job->num_alloc left at its smaller value?

avd_init_job() resets job->num_alloc to the initial slice count while retaining the larger job->buf.size, so taking the commit_slices branch on a later frame updates h264_ctx->alloc_slice_num without updating job->num_alloc, causing avd_end_segment() to fail once job->num reaches the old job->num_alloc.

[ ... ]

Quoted 28 lines
drivers/media/platform/apple/avd/avd-h264.c new file +28 -0
+static int avd_h264_run(struct avd_ctx *ctx)
+{
+	struct avd_h264_ctx *h264_ctx = ctx->priv;
+	struct v4l2_h264_reflist_builder reflist_builder;
+	struct avd_h264_run run;
+	struct vb2_v4l2_buffer *src;
+	void *slice;
+	int ret;
+
+	avd_h264_run_preamble(ctx, &run);
+
+	src = v4l2_m2m_next_src_buf(ctx->fh.m2m_ctx);
+	slice = vb2_plane_vaddr(&src->vb2_buf, 0);
+	if (!slice) {
+		dev_err_ratelimited(ctx->dev->dev, "could not get slice vaddr");
+		ret = -EINVAL;
+		goto postamble;
+	}
+
+	if (ctx->job.segments &&
+	    h264_ctx->slice_num >= h264_ctx->alloc_slice_num) {
+		ret = avd_h264_realloc_slices(ctx);
+		if (ret)
+			goto postamble;
+	} else if (h264_ctx->slice_num >= h264_ctx->alloc_slice_num) {
+		ret = -EINVAL;
+		goto postamble;
+	}

drivers/media/platform/apple/avd/avd-h264.c line 742

Quoted 10 lines
drivers/media/platform/apple/avd/avd-h264.c new file +10 -0
+
+	h264_ctx->active_slice = &h264_ctx->slices[h264_ctx->slice_num];
+	ret = avd_buf_alloc(ctx->dev, h264_ctx->active_slice,
+			    vb2_get_plane_payload(&src->vb2_buf, 0));
+	if (ret)
+		goto postamble;
+
+	memcpy(h264_ctx->active_slice->cpu, slice,
+	       h264_ctx->active_slice->size);
+	h264_ctx->slice_num++;

[Severity: Medium]
Does incrementing h264_ctx->slice_num before validating the slice and frame state wedge the context after errors on held buffers?

When an error occurs in avd_h264_run() on a buffer with V4L2_BUF_FLAG_M2M_HOLD_CAPTURE_BUF set (for example, first_mb_in_slice != 0 when ctx->job.segments is NULL), avd_h264_done() skips resetting h264_ctx->slice_num because it checks only
!(src_buf->flags & V4L2_BUF_FLAG_M2M_HOLD_CAPTURE_BUF) and ignores result == VB2_BUF_STATE_ERROR. Once h264_ctx->slice_num reaches h264_ctx->alloc_slice_num with ctx->job.segments still NULL, the else if (h264_ctx->slice_num >= h264_ctx->alloc_slice_num) branch permanently rejects every subsequent buffer with -EINVAL. Similarly, starting a new frame (first_mb_in_slice == 0) after an unsubmitted multi-slice frame resets ctx->job.num in avd_init_job() without resetting h264_ctx->slice_num.

drivers/media/platform/apple/avd/avd-h264.c line 753

Quoted 11 lines
drivers/media/platform/apple/avd/avd-h264.c new file +11 -0
+
+	/* Build the P/B{0,1} ref lists. */
+	v4l2_h264_init_reflist_builder(&reflist_builder, run.decode_params,
+				       run.sps, run.decode_params->dpb);
+
+	run.num_valid = reflist_builder.num_valid;
+	run.cur_poc = reflist_builder.cur_pic_order_count;
+
+	v4l2_h264_build_p_ref_list(&reflist_builder, h264_ctx->reflists.p);
+	v4l2_h264_build_b_ref_lists(&reflist_builder, h264_ctx->reflists.b0,
+				    h264_ctx->reflists.b1);

[Severity: Low]
h264_ctx->reflists is populated on every slice here, but it is never read anywhere in the driver because stream_slice() uses sl->ref_pic_list0 and sl->ref_pic_list1 directly. Can h264_ctx->reflists and the v4l2_h264_build_{p,b}_ref_list*() calls be dropped, and v4l2_h264_init_reflist_builder() moved under is_new_frame()?

[ ... ]

drivers/media/platform/apple/avd/avd-h264.c line 784

Quoted 6 lines
drivers/media/platform/apple/avd/avd-h264.c new file +6 -0
+	ret = avd_submit_job(ctx);
+
+postamble:
+	avd_run_postamble(ctx, &run.base);
+	return ret;
+}

[Severity: Medium]
Can the decode completion interrupt race with avd_run_postamble() after avd_submit_job() kicks the hardware?

CPU0 CPU1 (threaded IRQ)
avd_h264_run()
avd_submit_job(ctx)

    writel(..., AVD_REG_MBOX1_SUBMIT)
                                      avd_irq_handler()
                                        avd_job_finish()
                                          ...
                                            vb2_buffer_done(&src->vb2_buf, ...)
                                              media_request_object_unbind()
                                                req_obj->req = NULL
  avd_run_postamble(ctx, &run.base)
    src_req = src->vb2_buf.req_obj.req
    if (src_req)                      <-- NULL, request never completed
      v4l2_ctrl_request_complete(...)

If the IRQ handler finishes the job before avd_run_postamble() runs, vb2_buffer_done() unbinds src->vb2_buf.req_obj and clears req_obj.req to NULL, so v4l2_ctrl_request_complete() is skipped and userspace polling on the media_request fd hangs. Calling avd_run_postamble() before avd_submit_job() avoids this race.

Quoted 6 lines
drivers/media/platform/apple/avd/avd-h264.c new file +6 -0
+
+static void avd_h264_done(struct avd_ctx *ctx, struct vb2_v4l2_buffer *src_buf,
+			  struct vb2_v4l2_buffer *dst_buf,
+			  enum vb2_buffer_state result)
+{
+	struct avd_dev *avd = ctx->dev;

drivers/media/platform/apple/avd/avd-h264.c line 800

Quoted 10 lines
drivers/media/platform/apple/avd/avd-h264.c new file +10 -0
+	struct avd_h264_ctx *h264_ctx = ctx->priv;
+	int i;
+
+	if (!(src_buf->flags & V4L2_BUF_FLAG_M2M_HOLD_CAPTURE_BUF)) {
+		for (i = 0; i < h264_ctx->slice_num; i++)
+			avd_buf_free(avd, &h264_ctx->slices[i]);
+		h264_ctx->slice_num = 0;
+		ctx->job.segments = NULL;
+	}
+}

[Severity: Medium]
Does freeing every slice buffer in avd_h264_done() force a dma_alloc_coherent() and dma_free_coherent() (with DART IOMMU map/unmap and IOTLB flush) on every slice of every frame?

avd_buf_alloc() already reuses an existing allocation when buf->cpu && size <= buf->size, but avd_h264_done() frees all h264_ctx->slices[i] buffers after each frame because stream_slice() uses h264_ctx->active_slice->size as the slice payload length. Also, stream_slice() scans for emulation prevention bytes byte-by-byte through the non-cacheable h264_ctx->active_slice->cpu coherent mapping instead of scanning the cacheable vb2_plane_vaddr() buffer before copying.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=7
#13 lore raw

PATCH v4 8/17 media: apple: avd: add vp9 support

In reply to Sofus Forstreuter

The fluster scores is 216/305 for VP9-TEST-VECTORS and 1/6 for VP9-TEST-VECTORS-HIGH.

---
 drivers/media/platform/apple/avd/Kconfig    |    1 +
 drivers/media/platform/apple/avd/Makefile   |    2 +-
 drivers/media/platform/apple/avd/avd-v4l2.c |   37 +
 drivers/media/platform/apple/avd/avd-vp9.c  | 1047 +++++++++++++++++++++++++++
 drivers/media/platform/apple/avd/avd.h      |   10 +
 5 files changed, 1096 insertions(+), 1 deletion(-)
drivers/media/platform/apple/avd/Kconfig +1 -0
index 8775e82150d0..c9e4d65b3d70 100644
@@ -10,6 +10,7 @@ config VIDEO_APPLE_AVD
 	select V4L2_MEM2MEM_DEV
 	select VIDEOBUF2_DMA_SG
 	select V4L2_H264
+	select V4L2_VP9
 	help
 	  Support for hardware video decoding on Apple Silicon devices using
 	  the Apple Video Decoder (AVD).
drivers/media/platform/apple/avd/Makefile +1 -1
index 482d43f8ea8e..26763a13edb2 100644
@@ -1,4 +1,4 @@
 # SPDX-License-Identifier: GPL-2.0-only
 
-apple-avd-y := avd-drv.o avd-v4l2.o avd-h264.o
+apple-avd-y := avd-drv.o avd-v4l2.o avd-h264.o avd-vp9.o
 obj-$(CONFIG_VIDEO_APPLE_AVD) += apple-avd.o
drivers/media/platform/apple/avd/avd-v4l2.c +37 -0
index 19fee769b3c0..d4ed64756c33 100644
@@ -265,6 +265,29 @@ static const struct avd_ctrls avd_h264_ctrls = {
 	.num_ctrls = ARRAY_SIZE(avd_h264_ctrl_descs),
 };
 
+static const struct avd_ctrl_desc avd_vp9_ctrl_descs[] = {
+	{
+		.cfg.id = V4L2_CID_STATELESS_VP9_FRAME,
+		.cfg.ops = &avd_ctrl_ops,
+	},
+	{
+		.cfg.id = V4L2_CID_STATELESS_VP9_COMPRESSED_HDR,
+	},
+	{
+		.cfg.id = V4L2_CID_MPEG_VIDEO_VP9_PROFILE,
+		.cfg.min = V4L2_MPEG_VIDEO_VP9_PROFILE_0,
+		.cfg.max = V4L2_MPEG_VIDEO_VP9_PROFILE_2,
+		.cfg.menu_skip_mask =
+			BIT(V4L2_MPEG_VIDEO_VP9_PROFILE_1),
+		.cfg.def = V4L2_MPEG_VIDEO_VP9_PROFILE_0,
+	},
+};
+
+static const struct avd_ctrls avd_vp9_ctrls = {
+	.ctrls = avd_vp9_ctrl_descs,
+	.num_ctrls = ARRAY_SIZE(avd_vp9_ctrl_descs),
+};
+
 static const struct avd_coded_fmt_desc avd_coded_fmts[] = {
 	{
 		.fourcc = V4L2_PIX_FMT_H264_SLICE,
@@ -281,6 +304,20 @@ static const struct avd_coded_fmt_desc avd_coded_fmts[] = {
 		.subsystem_flags = VB2_V4L2_FL_SUPPORTS_M2M_HOLD_CAPTURE_BUF,
 		.capability = AVD_CAPABILITY_H264,
 	},
+	{
+		.fourcc = V4L2_PIX_FMT_VP9_FRAME,
+		.frmsize = {
+			.min_width = 64,
+			.max_width = 16384,
+			.step_width = 64,
+			.min_height = 64,
+			.max_height = 16384,
+			.step_height = 16,
+		},
+		.ctrls = &avd_vp9_ctrls,
+		.ops = &avd_vp9_fmt_ops,
+		.capability = AVD_CAPABILITY_VP9,
+	},
 };
 
 static bool avd_is_capable(struct avd_ctx *ctx, unsigned int capability)
drivers/media/platform/apple/avd/avd-vp9.c new file +1047 -0

1,047 lines not on this page · raw message

drivers/media/platform/apple/avd/avd.h +10 -0
index f27a6de7126c..b56f0e3dc863 100644
@@ -62,6 +62,12 @@ struct avd_ctrls {
 	unsigned int num_ctrls;
 };
 
+struct avd_vp9_decoded_buffer_info {
+	unsigned short width;
+	unsigned short height;
+	unsigned int bit_depth : 4;
+};
+
 struct avd_comp {
 	u32 size;
 	/* relative offsets to start */
@@ -78,6 +84,9 @@ struct avd_decoded_buffer {
 		u64 aux_start;
 	} dma;
 	struct avd_comp comp;
+	union {
+		struct avd_vp9_decoded_buffer_info vp9;
+	};
 };
 
 struct avd_run {
@@ -224,6 +233,7 @@ void avd_run_preamble(struct avd_ctx *ctx, struct avd_run *run);
 void avd_run_postamble(struct avd_ctx *ctx, struct avd_run *run);
 
 extern const struct avd_coded_fmt_ops avd_h264_fmt_ops;
+extern const struct avd_coded_fmt_ops avd_vp9_fmt_ops;
 
 extern const struct v4l2_ctrl_ops avd_ctrl_ops;
 extern const struct v4l2_ioctl_ops avd_ioctl_ops;
Signature · 1 line
2.56.0
#14 lore raw

Re: [PATCH v4 08/17] media: apple: avd: add vp9 support

Thank you for your contribution! Sashiko AI review found 8 potential issues to consider: - [High] media: apple: avd: scratch buffer sizing mismatch in avd_vp9_alloc_bufs() - [High] media: apple…

Thank you for your contribution! Sashiko AI review found 8 potential issues to consider:
- [High] media: apple: avd: scratch buffer sizing mismatch in avd_vp9_alloc_bufs()
- [High] media: apple: avd: tile end coordinate underflow in set_tiles()
- [Medium] media: apple: avd: broken VP9_REF_SEL_ALT deduplication in make_flags1()
- [Medium] media: apple: avd: race between avd_submit_job() and avd_run_postamble()
- [Medium] media: apple: avd: uninitialized vp9 ref dimensions in set_refs()
- [Medium] media: apple: avd: missing try_ctrl and invalid format mapping in avd-vp9
- [Medium] media: apple: avd: stale VP9 controls used when avd_s_ctrl() returns -EBUSY
- [Medium] media: apple: avd: wrong segmentation and ref flags in make_flags1()
--

commit 3ff91a4acc8c11fb58895e9ab8c779033b9d3352
Author: Sofus Forstreuter <[email protected]>

media: apple: avd: add vp9 support

This commit adds stateless V4L2 VP9 decoding support to the Apple Video Decoder (AVD) driver.

drivers/media/platform/apple/avd/avd-v4l2.c static const struct avd_ctrls avd_h264_ctrls = { · line 272

Quoted 13 lines
drivers/media/platform/apple/avd/avd-v4l2.c +5 -0
index 19fee769b3c0c..d4ed64756c335 100644
@@ -265,6 +265,29 @@ static const struct avd_ctrls avd_h264_ctrls = {
 	.num_ctrls = ARRAY_SIZE(avd_h264_ctrl_descs),
 };
 
+static const struct avd_ctrl_desc avd_vp9_ctrl_descs[] = {
+	{
+		.cfg.id = V4L2_CID_STATELESS_VP9_FRAME,
+		.cfg.ops = &avd_ctrl_ops,
+	},

[Severity: Medium]
Can applying per-frame request controls fail in avd_s_ctrl() and leave avd_vp9_run_preamble() reading stale or zeroed ctrl->p_cur.p values?

V4L2_CID_STATELESS_VP9_FRAME is submitted in every frame's media request. If userspace allocates CAPTURE buffers before issuing a non-request VIDIOC_S_EXT_CTRLS(V4L2_CID_STATELESS_VP9_FRAME) (so ctx->image_fmt is still AVD_IMG_FMT_ANY), or if a request changes bit_depth or subsampling while CAPTURE buffers are allocated, v4l2_ctrl_request_setup() calls avd_s_ctrl() during avd_run_preamble():

drivers/media/platform/apple/avd/avd-v4l2.c:avd_s_ctrl() {
    ...
	image_fmt = desc->ops->get_image_fmt(ctx, ctrl);
	if (avd_image_fmt_changed(ctx, image_fmt)) {
		vq = v4l2_m2m_get_vq(ctx->fh.m2m_ctx,
				     V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE);
		if (vb2_is_busy(vq))
			return -EBUSY;
    ...
}

When avd_s_ctrl() returns -EBUSY, v4l2_ctrl_request_setup() aborts before updating ctrl->p_cur on V4L2_CID_STATELESS_VP9_FRAME and before applying V4L2_CID_STATELESS_VP9_COMPRESSED_HDR. Because avd_run_preamble() ignores the return value of v4l2_ctrl_request_setup(), avd_vp9_run_preamble() proceeds to decode the new bitstream with the previous frame's parameters and probability updates.

Quoted 5 lines
drivers/media/platform/apple/avd/avd-vp9.c new file +0 -0
new file mode 100644
index 0000000000000..822de33d6a512

[ ... ]

Quoted 12 lines
drivers/media/platform/apple/avd/avd-vp9.c new file +12 -0
+static void set_refs(struct avd_ctx *ctx, struct avd_vp9_run *run)
+{
+	const struct v4l2_ctrl_vp9_frame *frame = run->decode_params;
+	struct avd_decoded_buffer *dst, *ref_buf[4];
+	int xscale, yscale;
+
+	dst = vb2_to_avd_decoded_buf(&run->base.bufs.dst->vb2_buf);
+
+	ref_buf[0] = avd_get_ref_buf(ctx, &dst->base.vb, frame->last_frame_ts);
+	ref_buf[1] =
+		avd_get_ref_buf(ctx, &dst->base.vb, frame->golden_frame_ts);
+	ref_buf[2] = avd_get_ref_buf(ctx, &dst->base.vb, frame->alt_frame_ts);

drivers/media/platform/apple/avd/avd-vp9.c line 214

Quoted 10 lines
drivers/media/platform/apple/avd/avd-vp9.c new file +10 -0
+
+	push(0, "");
+	push(0, "");
+	push(0, "");
+
+	for (int i = 0; i < V4L2_VP9_NUM_FRAME_CTX - 1; i++) {
+		push(AVD_REF_FLAG_CONST, "hdr_9c_ref_100");
+		push(AVD_HDR_HEIGHT(ref_buf[i]->vp9.height - 1) |
+			     AVD_HDR_WIDTH(ref_buf[i]->vp9.width - 1),
+		     "hdr_70_ref_height_width");

[Severity: Medium]
Can ref_buf[i]->vp9.height - 1 and ref_buf[i]->vp9.width - 1 underflow to 0xffff here if an earlier decode job failed on that capture buffer?

In avd_vp9_run(), avd_vp9_run_preamble() calls avd_run_preamble() first, which copies the source timestamp to the destination buffer and sets copied_timestamp = 1 before validate_dec_params() and avd_init_job() run. If either check fails on a newly allocated capture buffer, avd_vp9_run() jumps to postamble before update_dec_buf_info() populates dst->vp9.width and dst->vp9.height. A subsequent inter frame referencing that timestamp will match the failed buffer via avd_get_ref_buf() with width and height still 0, programming 65536x65536 reference dimensions and zero scale factors into the hardware command stream.

Quoted 29 lines
drivers/media/platform/apple/avd/avd-vp9.c new file +29 -0
+
+		xscale = (ref_buf[i]->vp9.width << VP9_REF_SCALE_SHIFT) /
+			 dst->vp9.width;
+		yscale = (ref_buf[i]->vp9.height << VP9_REF_SCALE_SHIFT) /
+			 dst->vp9.height;
+		push(AVD_HDR_HEIGHT(xscale) | AVD_HDR_WIDTH(yscale),
+		     "ref_scale");
+
+		push_comp(ctx, ref_buf[i]);
+	}
+}
+
+static u32 make_flags1(struct avd_ctx *ctx, struct avd_vp9_run *run)
+{
+	struct avd_vp9_ctx *vp9_ctx = ctx->priv;
+	const struct v4l2_ctrl_vp9_frame *frame = run->decode_params;
+	struct avd_decoded_buffer *dst, *last, *golden, *alt;
+
+	dst = vb2_to_avd_decoded_buf(&run->base.bufs.dst->vb2_buf);
+	last = avd_get_ref_buf(ctx, &dst->base.vb, frame->last_frame_ts);
+	golden = avd_get_ref_buf(ctx, &dst->base.vb, frame->golden_frame_ts);
+	alt = avd_get_ref_buf(ctx, &dst->base.vb, frame->alt_frame_ts);
+	u32 flags;
+
+	/*
+	 * i have only seen V4L2_VP9_SIGN_BIAS_ALT, im simply guessing the
+	 * same applies for last and golden
+	 */
+	flags = VP9_REF_SEL_LAST(VP9_LAST_FRAME);

drivers/media/platform/apple/avd/avd-vp9.c line 253

Quoted 10 lines
drivers/media/platform/apple/avd/avd-vp9.c new file +10 -0
+
+	flags |= VP9_REF_BIAS_LAST(frame->ref_frame_sign_bias &
+				   V4L2_VP9_SIGN_BIAS_LAST);
+	flags |= VP9_REF_SEL_GOLDEN(golden == last ? VP9_LAST_FRAME :
+						     VP9_GOLDEN_FRAME);
+	flags |= VP9_REF_BIAS_GOLDEN(frame->ref_frame_sign_bias &
+				     V4L2_VP9_SIGN_BIAS_GOLDEN);
+	flags |= VP9_REF_SEL_ALT(alt != golden ? VP9_ALTREF_FRAME :
+				 alt != last   ? VP9_GOLDEN_FRAME :
+						 VP9_LAST_FRAME);

[Severity: Medium]
Does VP9_REF_SEL_ALT select VP9_ALTREF_FRAME instead of VP9_LAST_FRAME when alt == last and golden != last?

Testing alt != golden first immediately evaluates to VP9_ALTREF_FRAME whenever alt and golden differ, so the alt == last case is only reached when alt == golden == last. Checking alt == last ? VP9_LAST_FRAME :
(alt == golden ? VP9_GOLDEN_FRAME : VP9_ALTREF_FRAME) would deduplicate against both earlier reference slots.

Quoted 22 lines
drivers/media/platform/apple/avd/avd-vp9.c new file +22 -0
+	flags |= VP9_REF_BIAS_ALT(frame->ref_frame_sign_bias &
+				  V4L2_VP9_SIGN_BIAS_ALT);
+
+	flags |= VP9_REFERENCE_MODE(frame->reference_mode);
+
+	flags |= VP9_PARALLEL_DEC(frame->flags &
+				  V4L2_VP9_FRAME_FLAG_PARALLEL_DEC_MODE);
+	flags |= VP9_REFRESH_CTX(frame->flags &
+				 V4L2_VP9_FRAME_FLAG_REFRESH_FRAME_CTX);
+	flags |= VP9_INTERP_FILTER(frame->interpolation_filter);
+	flags |= VP9_HIGH_PREC_MV(frame->flags &
+				  V4L2_VP9_FRAME_FLAG_ALLOW_HIGH_PREC_MV);
+
+	flags |=
+		VP9_ERR_RES(frame->flags & V4L2_VP9_FRAME_FLAG_ERROR_RESILIENT);
+
+	flags |= VP9_SEG_ABS(frame->seg.flags &
+			     V4L2_VP9_SEGMENTATION_FLAG_ABS_OR_DELTA_UPDATE);
+	flags |= VP9_SEG_UDATA_TEMP(
+		frame->seg.flags & V4L2_VP9_SEGMENTATION_FLAG_UPDATE_DATA &&
+		frame->seg.flags & V4L2_VP9_SEGMENTATION_FLAG_TEMPORAL_UPDATE);
+	flags |= VP9_SEG_UPDATE_MAP(frame->seg.flags &

drivers/media/platform/apple/avd/avd-vp9.c line 285

Quoted 10 lines
drivers/media/platform/apple/avd/avd-vp9.c new file +10 -0
+				    V4L2_VP9_SEGMENTATION_FLAG_UPDATE_MAP);
+	flags |= VP9_SEG_ENABLED(frame->seg.flags &
+				 V4L2_VP9_SEGMENTATION_FLAG_ENABLED);
+
+	flags |= VP9_HAS_REF(
+		!(frame->flags & V4L2_VP9_FRAME_FLAG_ERROR_RESILIENT) &&
+		!(frame->flags & V4L2_VP9_FRAME_FLAG_KEY_FRAME) &&
+		vp9_ctx->last.valid &&
+		vp9_ctx->last.flags & V4L2_VP9_FRAME_FLAG_SHOW_FRAME &&
+		!(vp9_ctx->last.flags & V4L2_VP9_FRAME_FLAG_KEY_FRAME));

[Severity: Medium]
Should VP9_SEG_UDATA_TEMP be gated on V4L2_VP9_SEGMENTATION_FLAG_UPDATE_MAP rather than V4L2_VP9_SEGMENTATION_FLAG_UPDATE_DATA, and should VP9_HAS_REF also exclude V4L2_VP9_FRAME_FLAG_INTRA_ONLY?

In the VP9 specification (sections 6.2.11 and 6.4.14), segmentation_temporal_update is a sub-flag of segmentation_update_map and is independent of segmentation_update_data; when a frame temporally updates the segment map while reusing existing feature data, leaving VP9_SEG_UDATA_TEMP cleared causes the hardware boolean decoder to misparse segment IDs. In addition, VP9_HAS_REF only checks for V4L2_VP9_FRAME_FLAG_KEY_FRAME on frame->flags and vp9_ctx->last.flags, even though intra-only frames cannot use or provide temporal MV references (and set_header() skips set_refs() when V4L2_VP9_FRAME_FLAG_INTRA_ONLY is set).

[ ... ]

Quoted 2 lines
drivers/media/platform/apple/avd/avd-vp9.c new file +2 -0
+static int set_tiles(struct avd_ctx *ctx, struct avd_vp9_run *run)
+{

[ ... ]

Quoted 27 lines
drivers/media/platform/apple/avd/avd-vp9.c new file +27 -0
+	/* 6.2.6 Compute image size syntax */
+	u32 sb_64_cols = (((frame->frame_width_minus_1 + 8) >> 3) + 7) >> 3;
+	u32 sb_64_rows = (((frame->frame_height_minus_1 + 8) >> 3) + 7) >> 3;
+
+	for (int row = 0; row < num_tile_rows; row++)
+		for (int col = 0; col < num_tile_cols; col++) {
+			if (row == num_tile_rows - 1 &&
+			    col == num_tile_cols - 1) {
+				tile_size = size;
+			} else {
+				if (size < 4)
+					return -EINVAL;
+				tile_size = get_unaligned_be32(&data[offset]);
+				if (tile_size > size - 4)
+					return -EINVAL;
+				offset += 4;
+				size -= 4;
+			}
+
+			coded_in = run->base.coded_in + offset;
+			push(AVD_OP_CODED_DATA | AVD_OP_CODED_IN_HI(coded_in),
+			     "cm3_cmd_set_slice_data");
+			push(AVD_OP_CODED_IN_LO(coded_in), "coded_in");
+			push(tile_size, "til_ab8_tile_size");
+			push(AVD_OP_SL_DIM_START |
+				     AVD_OP_SL_DIM_START_Y((row * sb_64_rows) /
+							   num_tile_rows) |

drivers/media/platform/apple/avd/avd-vp9.c line 499

Quoted 10 lines
drivers/media/platform/apple/avd/avd-vp9.c new file +10 -0
+				     AVD_OP_SL_DIM_START_X((col * sb_64_cols) /
+							   num_tile_cols),
+			     "i");
+
+			push(AVD_SL_DIM_END_COL(col) |
+				     AVD_SL_DIM_END_Y(((row + 1) * sb_64_rows) /
+							      num_tile_rows - 1) |
+				     AVD_SL_DIM_END_X(((col + 1) * sb_64_cols) /
+							      num_tile_cols - 1),
+			     "til_ac0_tile_dims");

[Severity: High]
Can ((row + 1) * sb_64_rows) / num_tile_rows - 1 and
((col + 1) * sb_64_cols) / num_tile_cols - 1 underflow when num_tile_rows

Quoted 1 line

sb_64_rows or num_tile_cols > sb_64_cols?

validate_vp9_frame() allows tile_rows_log2 up to 2 (num_tile_rows = 4) and tile_cols_log2 up to 6 (num_tile_cols = 64) regardless of frame size, and validate_dec_params() allows frames down to 64x64 (sb_64_rows = 1, sb_64_cols = 1). When num_tile_rows > sb_64_rows or num_tile_cols > sb_64_cols, the integer division at row = 0 or col = 0 evaluates to 0 and subtracting 1 underflows to 0xfff in AVD_SL_DIM_END_Y or AVD_SL_DIM_END_X.

[ ... ]

Quoted 36 lines
drivers/media/platform/apple/avd/avd-vp9.c new file +36 -0
+static int validate_dec_params(struct avd_ctx *ctx,
+			       const struct v4l2_ctrl_vp9_frame *dec_params)
+{
+	unsigned int aligned_width, aligned_height;
+
+	if (dec_params->bit_depth > 10)
+		/* not implemented */
+		return -EINVAL;
+
+	if (dec_params->profile == 1 || dec_params->profile > 2)
+		return -EINVAL;
+
+	if (dec_params->frame_height_minus_1 + 1 < 64 ||
+	    dec_params->frame_width_minus_1 + 1 < 64)
+		return -EINVAL;
+
+	aligned_width = round_up(dec_params->frame_width_minus_1 + 1, 64);
+	aligned_height = round_up(dec_params->frame_height_minus_1 + 1, 16);
+
+	/*
+	 * Userspace should update the capture/decoded format when the
+	 * resolution changes.
+	 */
+	if (aligned_width != ctx->decoded_fmt.fmt.pix_mp.width ||
+	    aligned_height != ctx->decoded_fmt.fmt.pix_mp.height) {
+		dev_err(ctx->dev->dev,
+			"unexpected bitstream resolution %dx%d\n",
+			aligned_width, aligned_height);
+		return -EINVAL;
+	}
+
+	return 0;
+}
+
+static int avd_vp9_alloc_bufs(struct avd_ctx *ctx)
+{

drivers/media/platform/apple/avd/avd-vp9.c line 666

Quoted 10 lines
drivers/media/platform/apple/avd/avd-vp9.c new file +10 -0
+	struct avd_dev *avd = ctx->dev;
+	struct avd_vp9_ctx *vp9_ctx = ctx->priv;
+	int ret, w, h, bit_depth;
+
+	w = fmt_width(ctx);
+	h = fmt_height(ctx);
+	bit_depth = (ctx->image_fmt == AVD_IMG_FMT_420_10BIT ||
+		     ctx->image_fmt == AVD_IMG_FMT_422_10BIT) ?
+			    10 :
+			    8;

[Severity: High]
Can the hardware write past the end of the scratch DMA buffers in vp9_ctx->bufs when ctx->decoded_fmt or dec_params->bit_depth exceeds the OUTPUT format dimensions or ctx->image_fmt used at OUTPUT STREAMON?

avd_vp9_alloc_bufs() runs only once when VIDIOC_STREAMON is called on the OUTPUT queue, sizing color, ip_above, lf_above, seg, lf_left, lf_left_info, az_left, and above_info from ctx->coded_fmt (fmt_width(ctx) and fmt_height(ctx)) and ctx->image_fmt. However, avd_try_capture_fmt() allows ctx->decoded_fmt on the CAPTURE queue to be larger than ctx->coded_fmt (including after a mid-stream CAPTURE resolution change while OUTPUT remains streaming), and VIDIOC_STREAMON(OUTPUT) can run while ctx->image_fmt is still AVD_IMG_FMT_ANY (allocating for bit_depth = 8) before a 10-bit frame is submitted. Because validate_dec_params() only checks aligned_width and aligned_height against ctx->decoded_fmt and allows any dec_params->bit_depth <= 10, set_header() will program the hardware for dimensions or a 10-bit depth larger than the allocated scratch buffers.

[ ... ]

Quoted 2 lines
drivers/media/platform/apple/avd/avd-vp9.c new file +2 -0
+static int avd_vp9_run(struct avd_ctx *ctx)
+{

[ ... ]

drivers/media/platform/apple/avd/avd-vp9.c line 798

Quoted 12 lines
drivers/media/platform/apple/avd/avd-vp9.c new file +12 -0
+	set_header(ctx, &run);
+	avd_end_segment(ctx, false);
+	ret = set_tiles(ctx, &run);
+	if (ret)
+		goto postamble;
+
+	ret = avd_submit_job(ctx);
+
+postamble:
+	avd_run_postamble(ctx, &run.base);
+	return ret;
+}

[Severity: Medium]
Can avd_irq_handler() finish the job before avd_run_postamble() runs, leaving the media request uncompleted?

CPU0 CPU1
avd_vp9_run()
avd_submit_job()

    writel(..., AVD_REG_MBOX1_SUBMIT)
                                      avd_irq_handler()
                                        avd_job_finish()
                                          ...
                                            vb2_buffer_done()
                                              media_request_object_unbind()
                                                obj->req = NULL

avd_run_postamble()
src_req = ...->req_obj.req
if (src_req) <-- NULL, skips v4l2_ctrl_request_complete()

When vb2_buffer_done() unbinds the source buffer first, run.base.bufs.src->vb2_buf.req_obj.req becomes NULL before avd_run_postamble() reads it, so v4l2_ctrl_request_complete() is skipped and the media request never completes. Calling avd_run_postamble() before avd_submit_job() (or saving and completing the request before kicking off the hardware) avoids this race.

[ ... ]

Quoted 20 lines
drivers/media/platform/apple/avd/avd-vp9.c new file +20 -0
+static enum avd_image_fmt avd_vp9_get_image_fmt(struct avd_ctx *ctx,
+						struct v4l2_ctrl *ctrl)
+{
+#define BIT_DEPTH(chroma)                                      \
+	(frame->bit_depth == 8 ? AVD_IMG_FMT_##chroma##_8BIT : \
+				 AVD_IMG_FMT_##chroma##_10BIT)
+	const struct v4l2_ctrl_vp9_frame *frame = ctrl->p_new.p_vp9_frame;
+
+	if (ctrl->id != V4L2_CID_STATELESS_VP9_FRAME)
+		return AVD_IMG_FMT_ANY;
+
+	/* 7.2.2 Color config semantics */
+	if (frame->flags & V4L2_VP9_FRAME_FLAG_X_SUBSAMPLING) {
+		if (frame->flags & V4L2_VP9_FRAME_FLAG_Y_SUBSAMPLING)
+			return BIT_DEPTH(420);
+		else
+			return BIT_DEPTH(422);
+	}
+
+	return AVD_IMG_FMT_ANY;

drivers/media/platform/apple/avd/avd-vp9.c line 1047

Quoted 10 lines
drivers/media/platform/apple/avd/avd-vp9.c new file +10 -0
+#undef BIT_DEPTH
+}
+
+const struct avd_coded_fmt_ops avd_vp9_fmt_ops = {
+	.start = avd_vp9_start,
+	.stop = avd_vp9_stop,
+	.run = avd_vp9_run,
+	.done = avd_vp9_done,
+	.get_image_fmt = avd_vp9_get_image_fmt,
+};

[Severity: Medium]
Should avd_vp9_fmt_ops implement .try_ctrl to reject unsupported profiles, bit depths, subsampling, and dimensions at control validation time, and should avd_vp9_get_image_fmt() avoid mapping 4:2:2 or 12-bit frames to supported CAPTURE formats?

Without .try_ctrl, VIDIOC_TRY_EXT_CTRLS, VIDIOC_S_EXT_CTRLS, and MEDIA_REQUEST_IOC_VALIDATE accept VP9 profile 1/3, 12-bit, 4:2:2, and sub-64x64 frames, and avd_vp9_get_image_fmt() maps 4:2:2 and 12-bit frames to AVD_IMG_FMT_422_* and 10-bit CAPTURE formats even though set_header() hardcodes 4:2:0 (AVD_HDR_COMMON_CHROMA_FORMAT(1)) and validate_dec_params() rejects profile 1, profile > 2, and bit_depth > 10 when the decode job runs.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=8
#15 lore raw

PATCH v4 9/17 media: apple: avd: add hevc support

In reply to Sofus Forstreuter

The fluster score is 145/147 for JCT-VC-HEVC_V1.

RPS_E_qualcomm_5 is failing, but should be supported.

---
 drivers/media/platform/apple/avd/Makefile   |    2 +-
 drivers/media/platform/apple/avd/avd-hevc.c | 1327 +++++++++++++++++++++++++++
 drivers/media/platform/apple/avd/avd-v4l2.c |   72 ++
 drivers/media/platform/apple/avd/avd.h      |    6 +
 4 files changed, 1406 insertions(+), 1 deletion(-)
drivers/media/platform/apple/avd/Makefile +1 -1
index 26763a13edb2..903b86c0fe5c 100644
@@ -1,4 +1,4 @@
 # SPDX-License-Identifier: GPL-2.0-only
 
-apple-avd-y := avd-drv.o avd-v4l2.o avd-h264.o avd-vp9.o
+apple-avd-y := avd-drv.o avd-v4l2.o avd-h264.o avd-vp9.o avd-hevc.o
 obj-$(CONFIG_VIDEO_APPLE_AVD) += apple-avd.o
drivers/media/platform/apple/avd/avd-hevc.c new file +1327 -0

1,327 lines not on this page · raw message

drivers/media/platform/apple/avd/avd-v4l2.c +72 -0

84 lines not on this page · raw message

drivers/media/platform/apple/avd/avd.h +6 -0
index b56f0e3dc863..f0a2e1ef756b 100644
@@ -68,6 +68,10 @@ struct avd_vp9_decoded_buffer_info {
 	unsigned int bit_depth : 4;
 };
 
+struct avd_hevc_decoded_buffer_info {
+	bool is_intra;
+};
+
 struct avd_comp {
 	u32 size;
 	/* relative offsets to start */
@@ -86,6 +90,7 @@ struct avd_decoded_buffer {
 	struct avd_comp comp;
 	union {
 		struct avd_vp9_decoded_buffer_info vp9;
+		struct avd_hevc_decoded_buffer_info hevc;
 	};
 };
 
@@ -233,6 +238,7 @@ void avd_run_preamble(struct avd_ctx *ctx, struct avd_run *run);
 void avd_run_postamble(struct avd_ctx *ctx, struct avd_run *run);
 
 extern const struct avd_coded_fmt_ops avd_h264_fmt_ops;
+extern const struct avd_coded_fmt_ops avd_hevc_fmt_ops;
 extern const struct avd_coded_fmt_ops avd_vp9_fmt_ops;
 
 extern const struct v4l2_ctrl_ops avd_ctrl_ops;
Signature · 1 line
2.56.0
#16 lore raw

Re: [PATCH v4 09/17] media: apple: avd: add hevc support

Thank you for your contribution! Sashiko AI review found 7 potential issues to consider: - [Critical] media: apple: avd: tile size underflow and heap OOB in avd_hevc_compute_tiles() - [High] media…

Thank you for your contribution! Sashiko AI review found 7 potential issues to consider:
- [Critical] media: apple: avd: tile size underflow and heap OOB in avd_hevc_compute_tiles()
- [High] media: apple: avd: missing SPS block size and dimension validation
- [High] media: apple: avd: wrong collocated MV DMA address in stream_slice_mv()
- [High] media: apple: avd: unvalidated slice offsets and sizes in stream_slices()
- [Medium] media: apple: avd: wrong tile row bound and tile tracking in stream_slices()
- [Medium] media: apple: avd: frame intra state derived only from slice 0 in set_header()
- [Medium] media: apple: avd: per-frame high-order alloc in avd_hevc_compute_tiles()
--

commit 2e52bc9684c90021ba77b2d13dbe5c1acec46975
Author: Sofus Forstreuter <[email protected]>

media: apple: avd: add hevc support

This commit adds stateless V4L2 HEVC decoding support to the Apple Video Decoder (AVD) driver.

Quoted 6 lines
drivers/media/platform/apple/avd/avd-hevc.c new file +0 -0
new file mode 100644
index 0000000000000..fa9fc61a1c07f
@@ -0,0 +1,1327 @@

[ ... ]

Quoted 16 lines
drivers/media/platform/apple/avd/avd-hevc.c new file +16 -0
+static void set_header(struct avd_ctx *ctx, struct avd_hevc_run *run)
+{
+	const struct v4l2_ctrl_hevc_sps *sps = run->sps;
+	struct avd_dev *avd = ctx->dev;
+	struct avd_hevc_ctx *hevc_ctx = ctx->priv;
+	u32 bytesperline;
+	u32 width = sps->pic_width_in_luma_samples;
+	u32 height = sps->pic_height_in_luma_samples;
+
+	bool is_intra = (*run->sl)[0].slice_type == V4L2_HEVC_SLICE_TYPE_I;
+
+	push(AVD_OP_HDR | AVD_OP_HDR_FLAG_DECOMP(ctx->decomp) |
+		     AVD_OP_HDR_FLAG_INTRA(is_intra) | AVD_OP_HDR_CONST |
+		     AVD_OP_HDR_FLAG_HIST(
+			     !(avd->variant->quirks & AVD_QUIRK_NO_HISTOGRAM)),
+	     "hdr_34_start_hdr");

[ ... ]

drivers/media/platform/apple/avd/avd-hevc.c line 369

Quoted 2 lines
drivers/media/platform/apple/avd/avd-hevc.c new file +2 -0
+	if (!is_intra)
+		stream_refs(ctx, run);

[Severity: Medium]
Does checking only (*run->sl)[0].slice_type in set_header() and update_dec_buf_info() misclassify a multi-slice frame when slice 0 is an I slice and a later slice is a P or B slice? In that case set_header() sets AVD_OP_HDR_FLAG_INTRA(true) and skips stream_refs(), omitting reference frame and motion vector addresses needed by the later inter slices, and update_dec_buf_info() marks dst->hevc.is_intra = true, which disables temporal MVP when later frames reference this buffer.

[ ... ]

Quoted 4 lines
drivers/media/platform/apple/avd/avd-hevc.c new file +4 -0
+static void stream_slice_mv(struct avd_ctx *ctx, struct avd_hevc_run *run,
+			    const struct v4l2_ctrl_hevc_slice_params *sl,
+			    bool is_first)
+{

[ ... ]

drivers/media/platform/apple/avd/avd-hevc.c line 603

Quoted 7 lines
drivers/media/platform/apple/avd/avd-hevc.c new file +7 -0
+	if (ref_valid) {
+		dma_addr_t mv_color_addr = ref->dma.y +
+			(ref->base.vb.planes[0].length -
+			 mv_color_size(fmt_width(ctx), fmt_height(ctx)));
+		pusha(mv_color_addr, "mv_colo", 0);
+	}
+}

[Severity: High]
Should stream_slice_mv() push ref->dma.aux_start here, matching dst->dma.aux_start in stream_refs()?

ref->base.vb is struct vb2_v4l2_buffer, so when a VB2_MEMORY_DMABUF capture buffer is queued with v4l2_plane.length == 0, __prepare_dmabuf() populates vb2_buf.planes[0].length while leaving ref->base.vb.planes[0].length at 0. Subtracting mv_color_size() then underflows in u32 and points mv_color_addr ~4 GiB past ref->dma.y, causing an IOMMU fault or reading wrong collocated motion vectors (which also happens whenever the buffer is page-aligned or an Apple interchange pixel format is used).

[ ... ]

Quoted 26 lines
drivers/media/platform/apple/avd/avd-hevc.c new file +26 -0
+static void compute_tiles_non_uniform(struct avd_hevc_run *run,
+				      u16 log2_min_cb_size, u16 width,
+				      u16 height, s32 pic_in_cts_width,
+				      s32 pic_in_cts_height, u16 *column_width,
+				      u16 *row_height)
+{
+	const struct v4l2_ctrl_hevc_pps *pps = run->pps;
+	unsigned int num_cols = v4l2_hevc_pps_num_tile_columns(pps);
+	unsigned int num_rows = v4l2_hevc_pps_num_tile_rows(pps);
+	s32 sum = 0;
+	int i;
+
+	/* The last tile entry is written after the loop, so iterate one less. */
+	for (i = 0; i < num_cols - 1; i++) {
+		column_width[i] = pps->column_width_minus1[i] + 1;
+		sum += column_width[i];
+	}
+	column_width[i] = pic_in_cts_width - sum;
+
+	sum = 0;
+	for (i = 0; i < num_rows - 1; i++) {
+		row_height[i] = pps->row_height_minus1[i] + 1;
+		sum += row_height[i];
+	}
+	row_height[i] = pic_in_cts_height - sum;
+}

[ ... ]

Quoted 8 lines
drivers/media/platform/apple/avd/avd-hevc.c new file +8 -0
+static void compute_tile_ids(struct avd_hevc_run *run, u32 pic_in_ctbs_width,
+			     u32 *col_bd, u32 *row_bd, u32 *ctb_addr_rs_to_ts,
+			     u32 *tile_ids)
+{
+	const struct v4l2_ctrl_hevc_pps *pps = run->pps;
+	unsigned int rows = v4l2_hevc_pps_num_tile_rows(pps);
+	unsigned int cols = v4l2_hevc_pps_num_tile_columns(pps);
+	int j, i, y, x;

drivers/media/platform/apple/avd/avd-hevc.c line 799

Quoted 10 lines
drivers/media/platform/apple/avd/avd-hevc.c new file +10 -0
+	u32 tile_idx;
+
+	for (j = 0, tile_idx = 0; j < rows; j++)
+		for (i = 0; i < cols; i++, tile_idx++)
+			for (y = row_bd[j]; y < row_bd[j + 1]; y++)
+				for (x = col_bd[i]; x < col_bd[i + 1]; x++)
+					tile_ids[ctb_addr_rs_to_ts
+							 [y * pic_in_ctbs_width +
+							  x]] = tile_idx;
+}

[Severity: Critical]
Can column_width[i] and row_height[i] underflow in compute_tiles_non_uniform() and cause out-of-bounds heap writes to tile_ids[] in compute_tile_ids()?

Nothing checks that the sum of pps->column_width_minus1[i] + 1 is less than pic_in_cts_width (or that the sum of pps->row_height_minus1[i] + 1 is less than pic_in_cts_height). When sum exceeds pic_in_cts_width or pic_in_cts_height, assigning pic_in_cts_width - sum to a u16 wraps to a large value up to 65535, so col_bd[cols] and row_bd[rows] exceed the picture CTB dimensions while ctb_addr_rs_to_ts and tile_ids are only allocated with pic_in_ctbs_size elements.

[ ... ]

Quoted 2 lines
drivers/media/platform/apple/avd/avd-hevc.c new file +2 -0
+static int stream_slices(struct avd_ctx *ctx, struct avd_hevc_run *run)
+{

[ ... ]

Quoted 18 lines
drivers/media/platform/apple/avd/avd-hevc.c new file +18 -0
+	for (s = 0; s < run->num_slices; s++) {
+		sl = &(*run->sl)[s];
+		slice_segment_offset = 0;
+
+		/* entry_points are not needed for WPP */
+		to = tiles_enabled ? sl->num_entry_point_offsets + 1 : 1;
+
+		for (i = 0; i < to; i++) {
+			first_segment = i == 0;
+			first_slice = s == 0;
+
+			if (tiles_enabled && to > 1) {
+				if (i < sl->num_entry_point_offsets) {
+					size = (*run->entry_point_offsets)
+						       [entry_point_idx++];
+					new_offset = size;
+				} else {
+					size = sl->bit_size / 8 -

drivers/media/platform/apple/avd/avd-hevc.c line 870

Quoted 10 lines
drivers/media/platform/apple/avd/avd-hevc.c new file +10 -0
+					       sl->data_byte_offset -
+					       slice_segment_offset;
+					new_offset =
+						size + sl->data_byte_offset;
+				}
+			} else {
+				size = (sl->bit_size) / 8 -
+				       sl->data_byte_offset;
+				new_offset = size + sl->data_byte_offset;
+			}

[Severity: High]
Can size underflow or exceed the source buffer payload here before being passed to set_slice()?

If sl->data_byte_offset + slice_segment_offset > sl->bit_size / 8, size is negative and wraps to a large u32 in set_slice(), and neither stream_slices() nor set_slice() validates that offset + slice_segment_offset + sl->data_byte_offset + size fits within vb2_get_plane_payload(&run->base.bufs.src->vb2_buf, 0), allowing the hardware DMA engine to read past the end of the OUTPUT buffer.

Quoted 21 lines
drivers/media/platform/apple/avd/avd-hevc.c new file +21 -0
+
+			if (sl->slice_segment_addr >= pic_in_ctbs_size)
+				return -EINVAL;
+
+			tile_id = tile_info->tile_ids
+					  [tile_info->ctb_addr_rs_to_ts
+						   [sl->slice_segment_addr]];
+			last_tile_id =
+				first_slice ?
+					-1 :
+					tile_info->tile_ids
+						[tile_info->ctb_addr_rs_to_ts
+							 [(*run->sl)[s - 1]
+								  .slice_segment_addr]];
+
+			slice_flag = 0;
+			if (first_slice || tile_id != last_tile_id ||
+			    !first_segment)
+				slice_flag |= NEW_TILE_ID;
+
+			if (first_segment)

drivers/media/platform/apple/avd/avd-hevc.c line 901

Quoted 10 lines
drivers/media/platform/apple/avd/avd-hevc.c new file +10 -0
+				slice_flag |= NEW_SLICE;
+
+			vflip = false;
+			hflip = false;
+
+			row = pos / num_cols;
+			col = pos % num_cols;
+
+			if (row >= HEVC_MAX_TILE_ROWS)
+				return -EINVAL;

[Severity: Medium]
Should row be checked against v4l2_hevc_pps_num_tile_rows(pps) rather than HEVC_MAX_TILE_ROWS, and should last_tile_id track the tile where the previous segment ended instead of (*run->sl)[s - 1].slice_segment_addr?

compute_bd() only populates tile_info->row_bd[0..rows], so when rows < HEVC_MAX_TILE_ROWS and pos reaches rows * num_cols (which can also happen if slice s - 1 spanned multiple tiles and slice s starts in the tile where slice s - 1 ended, falsely setting NEW_TILE_ID and incrementing pos), submit_slice_segment() reads row_bd[row + 1] == 0 and underflows AVD_SL_DIM_END_Y(row_bd[row + 1] - 1) to 0xfff.

[ ... ]

Quoted 16 lines
drivers/media/platform/apple/avd/avd-hevc.c new file +16 -0
+static int avd_hevc_validate_sps(struct avd_ctx *ctx,
+				 const struct v4l2_ctrl_hevc_sps *sps)
+{
+	if (sps->pic_width_in_luma_samples > ctx->coded_fmt.fmt.pix_mp.width ||
+	    sps->pic_height_in_luma_samples > ctx->coded_fmt.fmt.pix_mp.height)
+		return -EINVAL;
+
+	if (sps->bit_depth_chroma_minus8 != sps->bit_depth_luma_minus8)
+		return -EINVAL;
+
+	if (sps->bit_depth_luma_minus8 > 2)
+		/* not implemented */
+		return -EINVAL;
+
+	return 0;
+}

[ ... ]

Quoted 10 lines
drivers/media/platform/apple/avd/avd-hevc.c new file +10 -0
+static int avd_hevc_compute_tiles(struct avd_ctx *ctx, struct avd_hevc_run *run)
+{
+	const struct v4l2_ctrl_hevc_sps *sps = run->sps;
+	const struct v4l2_ctrl_hevc_pps *pps = run->pps;
+	bool tiles_enabled;
+	struct avd_hevc_tile_info *tile_info = &run->tile_info;
+	u16 log2_min_cb_size, width, height;
+	u32 max_cu_width, pic_in_ctbs_width, pic_in_ctbs_height,
+		pic_in_ctbs_size;
+

drivers/media/platform/apple/avd/avd-hevc.c line 1143

Quoted 10 lines
drivers/media/platform/apple/avd/avd-hevc.c new file +10 -0
+	width = sps->pic_width_in_luma_samples;
+	height = sps->pic_height_in_luma_samples;
+
+	log2_min_cb_size = sps->log2_min_luma_coding_block_size_minus3 + 3;
+
+	max_cu_width = 1 << (sps->log2_diff_max_min_luma_coding_block_size +
+			     log2_min_cb_size);
+	pic_in_ctbs_width = (width + max_cu_width - 1) / max_cu_width;
+	pic_in_ctbs_height = (height + max_cu_width - 1) / max_cu_width;
+	pic_in_ctbs_size = pic_in_ctbs_height * pic_in_ctbs_width;

[Severity: High]
Can unvalidated SPS dimensions or coding block sizes cause shift overflow, division by zero, or ZERO_SIZE_PTR dereferences in avd_hevc_compute_tiles()?

avd_hevc_validate_sps() does not reject zero pic_width_in_luma_samples or pic_height_in_luma_samples (which is also the initial zeroed state if decoding starts before V4L2_CID_STATELESS_HEVC_SPS is set), nor does it bound log2_min_luma_coding_block_size_minus3 and log2_diff_max_min_luma_coding_block_size. Because avd_hevc_compute_tiles() runs before the !max_cu_width check in avd_hevc_alloc_scratch(), a large shift exponent overflows 1 << (...) and can divide by zero, while zero width or height yields pic_in_ctbs_size == 0 so kzalloc_objs() returns ZERO_SIZE_PTR, which compute_tile_ids() dereferences. In addition, avd_hevc_validate_sps() is only called from avd_hevc_try_ctrl(), so shrinking coded_fmt via VIDIOC_S_FMT after setting the SPS control leaves sps dimensions larger than
the active format.

drivers/media/platform/apple/avd/avd-hevc.c line 1155

Quoted 12 lines
drivers/media/platform/apple/avd/avd-hevc.c new file +12 -0
+
+	tiles_enabled = !!(pps->flags & V4L2_HEVC_PPS_FLAG_TILES_ENABLED);
+
+	tile_info->ctb_addr_rs_to_ts = kzalloc_objs(
+		*tile_info->ctb_addr_rs_to_ts, pic_in_ctbs_size, GFP_KERNEL);
+	if (!tile_info->ctb_addr_rs_to_ts)
+		return -ENOMEM;
+
+	tile_info->tile_ids = kzalloc_objs(*tile_info->tile_ids,
+					   pic_in_ctbs_size, GFP_KERNEL);
+	if (!tile_info->tile_ids)
+		return -ENOMEM;

[Severity: Medium]
Can we avoid allocating ctb_addr_rs_to_ts and tile_ids on every frame in avd_hevc_compute_tiles()?

Both arrays are allocated with kzalloc_objs(..., GFP_KERNEL) on every decode run even when tiles_enabled is false (reaching order-5 allocations for 4K with 16x16 CTBs, and up to 4-16 MB at the 16384x16384 max resolution). When tiles_enabled is true, stream_slices() only uses them as tile_info->tile_ids[tile_info->ctb_addr_rs_to_ts[sl->slice_segment_addr]], which just evaluates the tile index (tile_y * cols + tile_x) of sl->slice_segment_addr and can be computed directly from col_bd and row_bd without allocating either array or scanning all CTBs in the frame.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=9
#17 lore raw

PATCH v4 10/17 media: apple: avd: add av1 support

In reply to Sofus Forstreuter

AVD only supports decoding AV1 on newer SoCs, it does not support film grain.

The entropymode files are adapted from
commit c0d0e579db4e ("media: verisilicon: Add AV1 entropy helpers") with some extra tables being added and some tables being changed a bit.

The fluster score is 238/242 for AV1-TEST-VECTORS.

---
 drivers/media/platform/apple/avd/Makefile          |    3 +-
 .../media/platform/apple/avd/avd-av1-entropymode.c | 4698 ++++++++++++++++++++
 .../media/platform/apple/avd/avd-av1-entropymode.h |  284 ++
 drivers/media/platform/apple/avd/avd-av1.c         | 1432 ++++++
 drivers/media/platform/apple/avd/avd-v4l2.c        |   33 +
 drivers/media/platform/apple/avd/avd.h             |   14 +
 6 files changed, 6463 insertions(+), 1 deletion(-)
drivers/media/platform/apple/avd/Makefile +2 -1
index 903b86c0fe5c..b02ab2de3a11 100644
@@ -1,4 +1,5 @@
 # SPDX-License-Identifier: GPL-2.0-only
 
-apple-avd-y := avd-drv.o avd-v4l2.o avd-h264.o avd-vp9.o avd-hevc.o
+apple-avd-y := avd-drv.o avd-v4l2.o avd-h264.o avd-vp9.o avd-hevc.o avd-av1.o \
+	 avd-av1-entropymode.o
 obj-$(CONFIG_VIDEO_APPLE_AVD) += apple-avd.o
drivers/media/platform/apple/avd/avd-av1-entropymode.c new file +4698 -0

2,994 lines not on this page · raw message

drivers/media/platform/apple/avd/avd-av1-entropymode.h new file +284 -0

284 lines not on this page · raw message

drivers/media/platform/apple/avd/avd-av1.c new file +1432 -0

1,432 lines not on this page · raw message

drivers/media/platform/apple/avd/avd-v4l2.c +33 -0
index 19c33ad93db4..6f00a2a07c32 100644

Lines of this file are not shown. View the raw message.

drivers/media/platform/apple/avd/avd.h +14 -0
index f0a2e1ef756b..a49c00b244b0 100644

Lines of this file are not shown. View the raw message.

The rest of this diff is not shown. View the raw message.

Signature · 1 line
2.56.0

Part of the diff is not shown here. View the raw message.

#18 lore raw

Re: [PATCH v4 10/17] media: apple: avd: add av1 support

Thank you for your contribution! Sashiko AI review found 7 potential issues to consider: - [Critical] media: apple: avd: out-of-bounds memcpy in avd_av1_set_prob() - [High] media: apple: avd…

Thank you for your contribution! Sashiko AI review found 7 potential issues to consider:
- [Critical] media: apple: avd: out-of-bounds memcpy in avd_av1_set_prob()
- [High] media: apple: avd: division by zero in calc_upscale() and set_refs()
- [High] media: apple: avd: signedness bug and missing tile bounds in set_tiles()
- [High] media: apple: avd: 32-bit size overflows in avd_av1_alloc_work_bufs()
- [High] media: apple: avd: unallocated seg buffer and sentinel IOVAs in set_header()
- [Medium] media: apple: avd: stale shear params across loop in set_refs()
- [Medium] media: apple: avd: shift out of bounds in avd_av1_get_dist() --

commit 3d10bd41d7b615eda63f9315cb2299efb7e6934f
Author: Sofus Forstreuter <[email protected]>

media: apple: avd: add av1 support

This commit adds stateless V4L2 AV1 decoding support and entropy default tables to the Apple Video Decoder (AVD) driver.

Quoted 5 lines
drivers/media/platform/apple/avd/avd-av1.c new file +0 -0
new file mode 100644
index 0000000000000..c0706d981ce0e

[ ... ]

Quoted 11 lines
drivers/media/platform/apple/avd/avd-av1.c new file +11 -0
+static void
+avd_av1_dec_get_shear_params(const u32 *params, s64 *alpha,
+			     s64 *beta, s64 *gamma, s64 *delta)
+{
+	const int *mat = params;
+	short shift;
+	short y;
+	long long gv, dv;
+
+	if (mat[2] <= 0)
+		return;

[ ... ]

Quoted 10 lines
drivers/media/platform/apple/avd/avd-av1.c new file +10 -0
+static void set_refs(struct avd_ctx *ctx, struct avd_av1_run *run)
+{
+	struct avd_av1_ctx *av1_ctx = ctx->priv;
+	const struct v4l2_ctrl_av1_frame *frame = run->frame;
+	const struct v4l2_av1_global_motion *gm = &frame->global_motion;
+	int i, ref_idx;
+	struct avd_decoded_buffer *ref;
+	bool intrabc = !!(frame->flags & V4L2_AV1_FRAME_FLAG_ALLOW_INTRABC);
+	int height, width, x_scale, y_scale;
+	s64 alpha = 0, beta = 0, gamma = 0, delta = 0;

[ ... ]

drivers/media/platform/apple/avd/avd-av1.c line 406

Quoted 10 lines
drivers/media/platform/apple/avd/avd-av1.c new file +10 -0
+			avd_av1_dec_get_shear_params(&gm->params[ref_idx][0],
+						     &alpha, &beta, &gamma,
+						     &delta);
+			push(AV1_GM_PARAM_SHEAR0(beta) |
+				     AV1_GM_PARAM_SHEAR1(alpha),
+			     "ref_gm_beta_alpha");
+
+			push(AV1_GM_PARAM_SHEAR0(delta) |
+				     AV1_GM_PARAM_SHEAR1(gamma),
+			     "ref_gm_delta_gamma");

[Severity: Medium]
Does set_refs() push stale shear parameters from an earlier reference slot when a subsequent reference has gm->params[ref_idx][2] <= 0?

alpha, beta, gamma and delta are initialized once outside the loop, and avd_av1_dec_get_shear_params() returns early without zeroing them when mat[2] <= 0. Also, gm->params is __s32, so taking const u32 * in avd_av1_dec_get_shear_params() triggers a -Wpointer-sign warning.

Quoted 27 lines
drivers/media/platform/apple/avd/avd-av1.c new file +27 -0
+		}
+		push(AVD_REF_FLAG_CONST |
+			     AV1_REF_ORDER_HINT(
+				     intrabc ? 0 : frame->order_hints[ref_idx]),
+		     "ref_flag");
+		push(AVD_HDR_HEIGHT(ref->av1.height) |
+			     AVD_HDR_WIDTH(ref->av1.width),
+		     "ref_height_width");
+
+		x_scale = ((ref->av1.upscaled_width << AV1_REF_SCALE_SHIFT) +
+			   (width / 2)) /
+			  width;
+		y_scale = (((ref->av1.height + 1) << AV1_REF_SCALE_SHIFT) +
+			   (height / 2)) /
+			  height;
+		push(AV1_REF_SCALE_X(x_scale) | AV1_REF_SCALE_Y(y_scale),
+		     "ref_scale");
+
+		push_comp(ctx, ref);
+	}
+}
+
+static int avd_av1_get_dist(struct avd_av1_run *run, int a, int b)
+{
+	const struct v4l2_ctrl_av1_sequence *seq = run->seq;
+	int bits = seq->order_hint_bits - 1;
+	int diff, m;

drivers/media/platform/apple/avd/avd-av1.c line 443

Quoted 10 lines
drivers/media/platform/apple/avd/avd-av1.c new file +10 -0
+
+	if (!seq->order_hint_bits)
+		return 0;
+
+	diff = a - b;
+	m = 1 << bits;
+	diff = (diff & (m - 1)) - (diff & m);
+
+	return diff;
+}

[Severity: Medium]
Can 1 << bits overflow a 32-bit signed int in avd_av1_get_dist()?

Neither v4l2-ctrls-core.c nor avd_av1_validate_sequence() bounds seq->order_hint_bits to <= 8, so a userspace value above 8 overflows the 3-bit AV1_HDR_ORDER_HINT_BITS() field and a value above 31 triggers a shift-out-of-bounds in avd_av1_get_dist().

[ ... ]

Quoted 10 lines
drivers/media/platform/apple/avd/avd-av1.c new file +10 -0
+/* 7.16. Upscaling process */
+static void calc_upscale(int frame_width, int upscaled_width, int sub_x,
+			 int *step_x, int *initial_subpel_x)
+{
+	int downscaled_plane_w, upscaled_plane_w, err;
+
+	downscaled_plane_w = AV1_DIV_ROUND_UP_POW2(frame_width, sub_x);
+	upscaled_plane_w = AV1_DIV_ROUND_UP_POW2(upscaled_width, sub_x);
+	*step_x = ((downscaled_plane_w << SUPERRES_SCALE_BITS) +
+		   (upscaled_plane_w / 2)) /

drivers/media/platform/apple/avd/avd-av1.c line 625

Quoted 10 lines
drivers/media/platform/apple/avd/avd-av1.c new file +10 -0
+		  upscaled_plane_w;
+	err = (upscaled_plane_w * *step_x) -
+	      (downscaled_plane_w << SUPERRES_SCALE_BITS);
+	*initial_subpel_x = (-((upscaled_plane_w - downscaled_plane_w)
+			       << (SUPERRES_SCALE_BITS - 1)) +
+			     upscaled_plane_w / 2) /
+				    upscaled_plane_w +
+			    (1 << (SUPERRES_EXTRA_BITS - 1)) - err / 2;
+	*initial_subpel_x &= SUPERRES_SCALE_MASK;
+}

[Severity: High]
Can calc_upscale() and set_refs() divide by zero when userspace passes an unvalidated V4L2_CID_STATELESS_AV1_FRAME control?

set_header() unconditionally calls calc_upscale() with frame->upscaled_width, which is not validated by v4l2-ctrls-core.c or this driver; if upscaled_width is 0, upscaled_plane_w is 0. Similarly, in set_refs(), width and height are computed as frame_width_minus_1 + 1 and frame_height_minus_1 + 1, which wrap to 0 if either field is U32_MAX.

[ ... ]

Quoted 7 lines
drivers/media/platform/apple/avd/avd-av1.c new file +7 -0
+	pusha(run->addresses.probs_out, "probs_out", 0);
+	pusha(av1_ctx->bufs.probs.addr, "probs", 1);
+	pusha(av1_ctx->bufs.above_info.addr, "col", 0);
+	pusha(av1_ctx->bufs.seg.addr, "seg", 0);
+	/* make it obvious if its used */
+	pusha(0xb0b0b0b0, "", 1);
+	pusha(run->addresses.color, "w_color", 0);

[ ... ]

drivers/media/platform/apple/avd/avd-av1.c line 950

Quoted 5 lines
drivers/media/platform/apple/avd/avd-av1.c new file +5 -0
+	pusha(av1_ctx->bufs.lf_left.addr, "lf_left", 0);
+	pusha(av1_ctx->bufs.lf_left_info.addr, "lf_left_info", 1);
+	/* make it obvious if its used */
+	pusha(0xa0a0a0a0, "", 0);
+	pusha(av1_ctx->bufs.rf_above_info.addr, "rf_above_info", 0);

[Severity: High]
What happens if segmentation is enabled without V4L2_AV1_SEGMENTATION_FLAG_UPDATE_MAP, or if the hardware accesses the 0xb0b0b0b0 and 0xa0a0a0a0 slots?

avd_av1_alloc_work_bufs() only allocates av1_ctx->bufs.seg when V4L2_AV1_SEGMENTATION_FLAG_UPDATE_MAP is set, so enabling V4L2_AV1_SEGMENTATION_FLAG_ENABLED without UPDATE_MAP leaves seg.addr at 0 (or undersized after a resolution change), while the second segmentation map slot (where avd-vp9.c passes seg.addr) and the slot at 0xa0a0a0a0 push hardcoded bogus IOVAs into the command stream.

[ ... ]

Quoted 24 lines
drivers/media/platform/apple/avd/avd-av1.c new file +24 -0
+static int set_tiles(struct avd_ctx *ctx, struct avd_av1_run *run)
+{
+	const struct v4l2_ctrl_av1_frame *frame = run->frame;
+	const struct v4l2_ctrl_av1_sequence *seq = run->seq;
+	const struct v4l2_ctrl_av1_tile_group_entry *tile_group;
+	const struct v4l2_av1_tile_info *tile_info = &frame->tile_info;
+	dma_addr_t coded_in;
+	int row, col, sb_row, sb_col, tile_id, tile_row, tile_col;
+	int sb_shift =
+		seq->flags & V4L2_AV1_SEQUENCE_FLAG_USE_128X128_SUPERBLOCK ? 5 :
+									     4;
+
+	for (row = 0; row < tile_info->tile_rows; row++) {
+		for (col = 0; col < tile_info->tile_cols; col++) {
+			tile_id = row * tile_info->tile_cols + col;
+			tile_group = &run->tile_group[tile_id];
+			coded_in = run->base.coded_in +
+					      tile_group->tile_offset;
+			tile_row = tile_group->tile_row;
+			tile_col = tile_group->tile_col;
+
+			if (tile_col >= V4L2_AV1_MAX_TILE_COLS ||
+			    tile_row >= V4L2_AV1_MAX_TILE_ROWS)
+				return -EINVAL;

drivers/media/platform/apple/avd/avd-av1.c line 1010

Quoted 10 lines
drivers/media/platform/apple/avd/avd-av1.c new file +10 -0
+
+			push(AVD_OP_CODED_DATA | AVD_OP_CODED_IN_HI(coded_in),
+			     "tile_start");
+			push(AVD_OP_CODED_IN_LO(coded_in), "tile_addr");
+			push(tile_group->tile_size, "tile_size");
+
+			sb_row =
+				tile_info->mi_row_starts[tile_row] >> sb_shift;
+			sb_col =
+				tile_info->mi_col_starts[tile_col] >> sb_shift;

[Severity: High]
Can a negative tile_row or tile_col index tile_info arrays out of bounds in set_tiles()?

tile_group->tile_row and tile_group->tile_col are __u32 values from userspace assigned into signed int variables, so values >= 0x80000000U become negative, bypass the >= V4L2_AV1_MAX_TILE_ROWS/COLS check, and read before mi_row_starts[], mi_col_starts[], height_in_sbs_minus_1[] and width_in_sbs_minus_1[]. In addition, tile_row and tile_col are not checked against tile_info->tile_rows and tile_info->tile_cols, and tile_offset and tile_size are not checked against the source buffer payload size.

[ ... ]

Quoted 2 lines
drivers/media/platform/apple/avd/avd-av1.c new file +2 -0
+static int avd_av1_set_prob(struct avd_ctx *ctx, struct avd_av1_run *run)
+{

[ ... ]

Quoted 32 lines
drivers/media/platform/apple/avd/avd-av1.c new file +32 -0
+		memcpy(av1_ctx->bufs.probs.cpu,
+		       vaddr + AVD_AV1_CDFS_OFFSET(length, ref->av1.color_size),
+		       sizeof(struct avd_av1_cdfs));
+	}
+
+	length = dst->base.vb.vb2_buf.planes[0].length;
+	vaddr = vb2_plane_vaddr(&dst->base.vb.vb2_buf, 0);
+	if (!vaddr)
+		return -EINVAL;
+	/*
+	 * AVD writes nothing when DISABLE_FRAME_END_UPDATE_CDF is
+	 * enabled
+	 */
+	memcpy(vaddr + AVD_AV1_CDFS_OFFSET(length, dst->av1.color_size),
+	       av1_ctx->bufs.probs.cpu, sizeof(struct avd_av1_cdfs));
+	return 0;
+}
+
+static int avd_color_size(int h, int w)
+{
+	/*
+	 * in reality its dependent on quality
+	 * 64 with lower quality
+	 */
+	return ALIGN(w, 128) * ALIGN(h, 128) / 16;
+}
+
+static void update_dec_buf_info(struct avd_decoded_buffer *buf,
+				const struct v4l2_ctrl_av1_sequence *seq,
+				const struct v4l2_ctrl_av1_frame *frame)
+{
+	int i;

drivers/media/platform/apple/avd/avd-av1.c line 1111

Quoted 10 lines
drivers/media/platform/apple/avd/avd-av1.c new file +10 -0
+
+	buf->av1.width = frame->frame_width_minus_1;
+	buf->av1.height = frame->frame_height_minus_1;
+	buf->av1.upscaled_width = frame->upscaled_width;
+	buf->av1.bit_depth = seq->bit_depth;
+	buf->av1.frame_type = frame->frame_type;
+	buf->av1.intrabc = frame->flags & V4L2_AV1_FRAME_FLAG_ALLOW_INTRABC;
+
+	buf->av1.color_size = avd_color_size(frame->frame_width_minus_1 + 1,
+					     frame->frame_height_minus_1 + 1);

[Severity: Critical]
Can AVD_AV1_CDFS_OFFSET(length, dst->av1.color_size) underflow in avd_av1_set_prob() and avd_av1_run_preamble(), causing memcpy() and DMA to access memory outside the capture plane?

The capture buffer is sized from ctx->decoded_fmt.fmt.pix_mp, but unlike avd-vp9.c and avd-hevc.c, avd-av1.c never checks that frame->frame_width_minus_1 + 1 and frame->frame_height_minus_1 + 1 fit within the negotiated format (and avd_color_size() can also overflow 32-bit signed int). If userspace submits frame dimensions larger than the allocated capture buffer, ALIGN(color_size, AVD_ALIGN) + ALIGN(AVD_CDFS_SIZE, AVD_ALIGN) exceeds planes[0].length and AVD_AV1_CDFS_OFFSET() wraps around, writing sizeof(struct avd_av1_cdfs) bytes out of bounds before vaddr.

[ ... ]

Quoted 22 lines
drivers/media/platform/apple/avd/avd-av1.c new file +22 -0
+static int avd_av1_alloc_work_bufs(struct avd_ctx *ctx, struct avd_av1_run *run)
+{
+	struct avd_dev *avd = ctx->dev;
+	struct avd_av1_ctx *av1_ctx = ctx->priv;
+	const struct v4l2_ctrl_av1_frame *frame = run->frame;
+	const struct v4l2_ctrl_av1_sequence *seq = run->seq;
+	const struct v4l2_av1_tile_info *tile_info = &frame->tile_info;
+	u32 ret, max_sb_col = 0, max_sb_row = 0, i, sb_cols1 = 0, sb_cols2 = 0,
+		 sb;
+	u32 w = frame->frame_width_minus_1 + 1;
+	u32 h = frame->frame_height_minus_1 + 1;
+	u8 sb_shift =
+		seq->flags & V4L2_AV1_SEQUENCE_FLAG_USE_128X128_SUPERBLOCK ? 1 :
+									     0;
+	u8 bit_depth = seq->bit_depth;
+
+	for (i = 0; i < tile_info->tile_cols; i++) {
+		sb = tile_info->width_in_sbs_minus_1[i] + 1;
+		max_sb_col = sb > max_sb_col ? sb : max_sb_col;
+		sb_cols1 += ALIGN((sb << sb_shift) * 44, 128);
+		/* wrong alignment? */
+		sb_cols2 += ALIGN((sb << sb_shift) * 12, 128);

drivers/media/platform/apple/avd/avd-av1.c line 1190

Quoted 10 lines
drivers/media/platform/apple/avd/avd-av1.c new file +10 -0
+	}
+
+	max_sb_col <<= sb_shift;
+
+	ret = avd_buf_alloc(avd, &av1_ctx->bufs.mv_above_info, max_sb_col * 80);
+	if (ret)
+		return ret;
+
+	/* first frame this is always much smaller */
+	ret = avd_buf_alloc(avd, &av1_ctx->bufs.above_info, max_sb_col * 400);

[Severity: High]
Can the 32-bit size calculations in avd_av1_alloc_work_bufs() overflow and allocate undersized DMA scratch buffers?

width_in_sbs_minus_1[], height_in_sbs_minus_1[], frame_width_minus_1 and frame_height_minus_1 are unvalidated u32 fields from userspace. Large values can wrap 32-bit calculations such as sb_cols1, max_sb_col * 400, (ALIGN(h, ...) * ALIGN(w, ...)) / 128 * 3 and (max_sb_row * 72 + 1) * 2 * bit_depth to small non-zero sizes while the hardware is programmed with the unwrapped superblock dimensions.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=10
#19 lore raw

PATCH v4 11/17 arm64: dts: apple: t8103: add avd nodes

In reply to Sofus Forstreuter
---
 arch/arm64/boot/dts/apple/t8103.dtsi | 33 +++++++++++++++++++++++++++++++++
 1 file changed, 33 insertions(+)
arch/arm64/boot/dts/apple/t8103.dtsi +33 -0
index 5b68bf0df4e6..a37f135af616 100644
@@ -984,6 +984,39 @@ pinctrl_aop: pinctrl@24a820000 {
 				     <AIC_IRQ 274 IRQ_TYPE_LEVEL_HIGH>;
 		};
 
+		avd_dart: iommu@269010000 {
+			compatible = "apple,t8103-dart";
+			reg = <0x2 0x69010000 0x0 0x4000>;
+			interrupt-parent = <&aic>;
+			interrupts = <AIC_IRQ 547 IRQ_TYPE_LEVEL_HIGH>;
+			#iommu-cells = <1>;
+			power-domains = <&ps_avd_sys>;
+		};
+
+		video-codec@269070000 {
+			compatible = "apple,t8103-avd";
+			reg = <0x2 0x69070000 0x0 0x4000>,
+			      <0x2 0x69080000 0x0 0xc000>,
+			      <0x2 0x6908c000 0x0 0xc000>,
+			      <0x2 0x69098000 0x0 0x4000>,
+			      <0x2 0x69100000 0x0 0x10000>;
+			reg-names = "piodma", "code", "sram", "mbox", "ctrl";
+			interrupt-parent = <&aic>;
+			interrupts = <AIC_IRQ 540 IRQ_TYPE_LEVEL_HIGH>,
+				     <AIC_IRQ 541 IRQ_TYPE_LEVEL_HIGH>,
+				     <AIC_IRQ 542 IRQ_TYPE_LEVEL_HIGH>,
+				     <AIC_IRQ 543 IRQ_TYPE_LEVEL_HIGH>,
+				     <AIC_IRQ 544 IRQ_TYPE_LEVEL_HIGH>,
+				     <AIC_IRQ 545 IRQ_TYPE_LEVEL_HIGH>,
+				     <AIC_IRQ 546 IRQ_TYPE_LEVEL_HIGH>;
+			interrupt-names = "mbox0", "mbox1", "mbox2", "mbox3",
+					  "flag0", "flag1", "piodma";
+			iommus = <&avd_dart 0>, <&avd_dart 1>;
+			power-domains = <&ps_avd_sys>;
+			resets = <&ps_avd_sys>;
+			dma-coherent;
+		};
+
 		ans_mbox: mbox@277408000 {
 			compatible = "apple,t8103-asc-mailbox", "apple,asc-mailbox-v4";
 			reg = <0x2 0x77408000 0x0 0x4000>;
Signature · 1 line
2.56.0
#20 lore raw

Re: [PATCH v4 11/17] arm64: dts: apple: t8103: add avd nodes

Thank you for your contribution! Sashiko AI review found 4 potential issues to consider: - [Critical] media: apple: avd: out-of-bounds heap accesses in compute_tile_ids() - [Critical] media: apple…

Thank you for your contribution! Sashiko AI review found 4 potential issues to consider:
- [Critical] media: apple: avd: out-of-bounds heap accesses in compute_tile_ids()
- [Critical] media: apple: avd: missing input validation and stale state in avd-av1.c
- [Medium] arm64: dts: apple: t8103: undocumented dma-coherent on video-codec@269070000
- [Low] arm64: dts: apple: t8103: missing commit message description body
--

commit a42482d760146079b998f04577af5da5b0a27753
Author: Sofus Forstreuter <[email protected]>

Quoted 4 lines

arm64: dts: apple: t8103: add avd nodes

[Severity: Low]
This commit message has no changelog body describing the added avd_dart DART IOMMU and Apple Video Decoder nodes.

Quoted 30 lines
arch/arm64/boot/dts/apple/t8103.dtsi +22 -0
index 5b68bf0df4e6b..a37f135af616d 100644
@@ -984,6 +984,39 @@ pinctrl_aop: pinctrl@24a820000 {
 				     <AIC_IRQ 274 IRQ_TYPE_LEVEL_HIGH>;
 		};
 
+		avd_dart: iommu@269010000 {
+			compatible = "apple,t8103-dart";
+			reg = <0x2 0x69010000 0x0 0x4000>;
+			interrupt-parent = <&aic>;
+			interrupts = <AIC_IRQ 547 IRQ_TYPE_LEVEL_HIGH>;
+			#iommu-cells = <1>;
+			power-domains = <&ps_avd_sys>;
+		};
+
+		video-codec@269070000 {
+			compatible = "apple,t8103-avd";
+			reg = <0x2 0x69070000 0x0 0x4000>,
+			      <0x2 0x69080000 0x0 0xc000>,
+			      <0x2 0x6908c000 0x0 0xc000>,
+			      <0x2 0x69098000 0x0 0x4000>,
+			      <0x2 0x69100000 0x0 0x10000>;
+			reg-names = "piodma", "code", "sram", "mbox", "ctrl";
+			interrupt-parent = <&aic>;
+			interrupts = <AIC_IRQ 540 IRQ_TYPE_LEVEL_HIGH>,
+				     <AIC_IRQ 541 IRQ_TYPE_LEVEL_HIGH>,
+				     <AIC_IRQ 542 IRQ_TYPE_LEVEL_HIGH>,
+				     <AIC_IRQ 543 IRQ_TYPE_LEVEL_HIGH>,

arch/arm64/boot/dts/apple/t8103.dtsi pinctrl_aop: pinctrl@24a820000 { · line 1018

Quoted 10 lines
arch/arm64/boot/dts/apple/t8103.dtsi +10 -0
+				     <AIC_IRQ 544 IRQ_TYPE_LEVEL_HIGH>,
+				     <AIC_IRQ 545 IRQ_TYPE_LEVEL_HIGH>,
+				     <AIC_IRQ 546 IRQ_TYPE_LEVEL_HIGH>;
+			interrupt-names = "mbox0", "mbox1", "mbox2", "mbox3",
+					  "flag0", "flag1", "piodma";
+			iommus = <&avd_dart 0>, <&avd_dart 1>;
+			power-domains = <&ps_avd_sys>;
+			resets = <&ps_avd_sys>;
+			dma-coherent;
+		};

[Severity: Medium]
Does dma-coherent on video-codec@269070000 fail make dtbs_check? Documentation/devicetree/bindings/media/apple,avd.yaml sets
additionalProperties: false and does not list dma-coherent under properties.

[Severity: Critical]
Can exposing video-codec@269070000 allow unprivileged userspace to trigger out-of-bounds kernel heap reads and writes in the HEVC decoder via compute_tile_ids()?

When an HEVC decode request runs avd_device_run() -> avd_hevc_run() -> avd_hevc_compute_tiles(), compute_tiles_non_uniform() accumulates unvalidated pps->column_width_minus1[i] + 1 and pps->row_height_minus1[i] + 1 into sum and assigns the final u16 entry as pic_in_cts_width - sum and pic_in_cts_height - sum:

drivers/media/platform/apple/avd/avd-hevc.c:compute_tiles_non_uniform() {
	...
	for (i = 0; i < num_cols - 1; i++) {
		column_width[i] = pps->column_width_minus1[i] + 1;
		sum += column_width[i];
	}
	column_width[i] = pic_in_cts_width - sum;

	sum = 0;
	for (i = 0; i < num_rows - 1; i++) {
		row_height[i] = pps->row_height_minus1[i] + 1;
		sum += row_height[i];
	}
	row_height[i] = pic_in_cts_height - sum;
}

When sum >= pic_in_cts_width or sum >= pic_in_cts_height, the subtraction underflows u16 and compute_bd() produces col_bd and row_bd entries exceeding pic_in_ctbs_width and pic_in_ctbs_height. compute_tile_ids() then reads ctb_addr_rs_to_ts and writes tile_ids out of bounds on the kernel heap.

In addition, neither std_validate_compound() nor avd_hevc_validate_sps() rejects zero pic_width_in_luma_samples / pic_height_in_luma_samples or out-of-range log2_min_luma_coding_block_size_minus3 / log2_diff_max_min_luma_coding_block_size, so avd_hevc_compute_tiles() can hit an undefined shift or divide by zero when computing max_cu_width before avd_hevc_alloc_scratch() checks if (!max_cu_width), or allocate ZERO_SIZE_PTR for ctb_addr_rs_to_ts and tile_ids.

[Severity: Critical]
Can the AVD driver's AV1 decoder in drivers/media/platform/apple/avd/avd-av1.c write out of bounds in avd_av1_set_prob() when given unvalidated frame dimensions?

Neither validate_av1_frame() nor avd-av1.c checks frame_width_minus_1 + 1 and frame_height_minus_1 + 1 against the CAPTURE buffer dimensions, so dst->av1.color_size can exceed dst->base.vb.vb2_buf.planes[0].length and underflow AVD_AV1_CDFS_OFFSET(), causing memcpy() in avd_av1_set_prob() to write sizeof(struct avd_av1_cdfs) bytes before vaddr:

drivers/media/platform/apple/avd/avd-av1.c:avd_av1_set_prob() {
	...
	memcpy(vaddr + AVD_AV1_CDFS_OFFSET(length, dst->av1.color_size),
	       av1_ctx->bufs.probs.cpu, sizeof(struct avd_av1_cdfs));
}

In set_tiles(), assigning u32 tile_group->tile_row and tile_group->tile_col to signed int allows values >= 0x80000000 to become negative, bypass the V4L2_AV1_MAX_TILE_ROWS / V4L2_AV1_MAX_TILE_COLS upper-bound check, and index tile_info arrays out of bounds.

In calc_upscale(), an unvalidated frame->upscaled_width of 0 yields upscaled_plane_w == 0 and triggers an integer division by zero.

Finally, set_refs() declares alpha, beta, gamma and delta outside the reference loop, so when avd_av1_dec_get_shear_params() returns early on mat[2] <= 0, the iteration reuses stale shear parameters from an earlier reference frame.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=11
#21 lore raw

PATCH v4 12/17 arm64: dts: apple: t8112: add avd nodes

In reply to Sofus Forstreuter
---
 arch/arm64/boot/dts/apple/t8112.dtsi | 33 +++++++++++++++++++++++++++++++++
 1 file changed, 33 insertions(+)
arch/arm64/boot/dts/apple/t8112.dtsi +33 -0
index ec248ca052cb..bbf123c8e120 100644
@@ -987,6 +987,39 @@ pinctrl_aop: pinctrl@24a820000 {
 				     <AIC_IRQ 307 IRQ_TYPE_LEVEL_HIGH>;
 		};
 
+		avd_dart: iommu@269010000 {
+			compatible = "apple,t8110-dart";
+			reg = <0x2 0x69010000 0x0 0x4000>;
+			interrupt-parent = <&aic>;
+			interrupts = <AIC_IRQ 674 IRQ_TYPE_LEVEL_HIGH>;
+			#iommu-cells = <1>;
+			power-domains = <&ps_avd_sys>;
+		};
+
+		video-codec@269070000 {
+			compatible = "apple,t8112-avd";
+			reg = <0x2 0x69070000 0x0 0x4000>,
+			      <0x2 0x69080000 0x0 0x10000>,
+			      <0x2 0x69090000 0x0 0x10000>,
+			      <0x2 0x690a0000 0x0 0x4000>,
+			      <0x2 0x69100000 0x0 0x10000>;
+			reg-names = "piodma", "code", "sram", "mbox", "ctrl";
+			interrupt-parent = <&aic>;
+			interrupts = <AIC_IRQ 667 IRQ_TYPE_LEVEL_HIGH>,
+				     <AIC_IRQ 668 IRQ_TYPE_LEVEL_HIGH>,
+				     <AIC_IRQ 669 IRQ_TYPE_LEVEL_HIGH>,
+				     <AIC_IRQ 670 IRQ_TYPE_LEVEL_HIGH>,
+				     <AIC_IRQ 671 IRQ_TYPE_LEVEL_HIGH>,
+				     <AIC_IRQ 672 IRQ_TYPE_LEVEL_HIGH>,
+				     <AIC_IRQ 673 IRQ_TYPE_LEVEL_HIGH>;
+			interrupt-names = "mbox0", "mbox1", "mbox2", "mbox3",
+					  "flag0", "flag1", "piodma";
+			iommus = <&avd_dart 0>, <&avd_dart 1>;
+			power-domains = <&ps_avd_sys>;
+			resets = <&ps_avd_sys>;
+			dma-coherent;
+		};
+
 		ans_mbox: mbox@277408000 {
 			compatible = "apple,t8112-asc-mailbox", "apple,asc-mailbox-v4";
 			reg = <0x2 0x77408000 0x0 0x4000>;
Signature · 1 line
2.56.0
#22 lore raw

Re: [PATCH v4 12/17] arm64: dts: apple: t8112: add avd nodes

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [Low] arm64: dts: apple: t8112: undocumented dma-coherent on video-codec@269070000 - [Low] arm64: dts…

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [Low] arm64: dts: apple: t8112: undocumented dma-coherent on video-codec@269070000
- [Low] arm64: dts: apple: t8112: empty commit description body in changelog
--

commit 049acf5b80b3a89829c61860b34a6e3252cf17fb
Author: Sofus Forstreuter <[email protected]>

Quoted 4 lines

arm64: dts: apple: t8112: add avd nodes

[Severity: Low]
The commit message has no description body. Could a short changelog explaining the addition of the Apple Video Decoder and its DART IOMMU nodes for T8112 be added?

Quoted 29 lines
arch/arm64/boot/dts/apple/t8112.dtsi +21 -0
index ec248ca052cb2..bbf123c8e120e 100644
@@ -987,6 +987,39 @@ pinctrl_aop: pinctrl@24a820000 {
 				     <AIC_IRQ 307 IRQ_TYPE_LEVEL_HIGH>;
 		};
 
+		avd_dart: iommu@269010000 {
+			compatible = "apple,t8110-dart";
+			reg = <0x2 0x69010000 0x0 0x4000>;
+			interrupt-parent = <&aic>;
+			interrupts = <AIC_IRQ 674 IRQ_TYPE_LEVEL_HIGH>;
+			#iommu-cells = <1>;
+			power-domains = <&ps_avd_sys>;
+		};
+
+		video-codec@269070000 {
+			compatible = "apple,t8112-avd";
+			reg = <0x2 0x69070000 0x0 0x4000>,
+			      <0x2 0x69080000 0x0 0x10000>,
+			      <0x2 0x69090000 0x0 0x10000>,
+			      <0x2 0x690a0000 0x0 0x4000>,
+			      <0x2 0x69100000 0x0 0x10000>;
+			reg-names = "piodma", "code", "sram", "mbox", "ctrl";
+			interrupt-parent = <&aic>;
+			interrupts = <AIC_IRQ 667 IRQ_TYPE_LEVEL_HIGH>,
+				     <AIC_IRQ 668 IRQ_TYPE_LEVEL_HIGH>,
+				     <AIC_IRQ 669 IRQ_TYPE_LEVEL_HIGH>,

arch/arm64/boot/dts/apple/t8112.dtsi pinctrl_aop: pinctrl@24a820000 { · line 1020

Quoted 10 lines
arch/arm64/boot/dts/apple/t8112.dtsi +10 -0
+				     <AIC_IRQ 670 IRQ_TYPE_LEVEL_HIGH>,
+				     <AIC_IRQ 671 IRQ_TYPE_LEVEL_HIGH>,
+				     <AIC_IRQ 672 IRQ_TYPE_LEVEL_HIGH>,
+				     <AIC_IRQ 673 IRQ_TYPE_LEVEL_HIGH>;
+			interrupt-names = "mbox0", "mbox1", "mbox2", "mbox3",
+					  "flag0", "flag1", "piodma";
+			iommus = <&avd_dart 0>, <&avd_dart 1>;
+			power-domains = <&ps_avd_sys>;
+			resets = <&ps_avd_sys>;
+			dma-coherent;

[Severity: Low]
Does dma-coherent on video-codec@269070000 cause make dtbs_check to fail? Documentation/devicetree/bindings/media/apple,avd.yaml sets
additionalProperties: false and does not list dma-coherent: true under properties.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=12
#23 lore raw

PATCH v4 13/17 arm64: dts: apple: t8122: add avd nodes

In reply to Sofus Forstreuter
---
 arch/arm64/boot/dts/apple/t8122.dtsi | 33 +++++++++++++++++++++++++++++++++
 1 file changed, 33 insertions(+)
arch/arm64/boot/dts/apple/t8122.dtsi +33 -0
index 52257fa22631..5f73ad9b247e 100644
@@ -190,6 +190,39 @@ soc {
 		nonposted-mmio;
 		#size-cells = <2>;
 
+		avd_dart: iommu@289010000 {
+			compatible = "apple,t8122-dart", "apple,t8110-dart";
+			reg = <0x2 0x89010000 0x0 0x4000>;
+			interrupt-parent = <&aic>;
+			interrupts = <AIC_IRQ 686 IRQ_TYPE_LEVEL_HIGH>;
+			#iommu-cells = <1>;
+			power-domains = <&ps_avd_sys>;
+		};
+
+		video-codec@289070000 {
+			compatible = "apple,t8122-avd";
+			reg = <0x2 0x89070000 0x0 0x4000>,
+			      <0x2 0x89080000 0x0 0x10000>,
+			      <0x2 0x89090000 0x0 0x14000>,
+			      <0x2 0x890a4000 0x0 0x4000>,
+			      <0x2 0x89100000 0x0 0x10000>;
+			reg-names = "piodma", "code", "sram", "mbox", "ctrl";
+			interrupt-parent = <&aic>;
+			interrupts = <AIC_IRQ 679 IRQ_TYPE_LEVEL_HIGH>,
+				     <AIC_IRQ 680 IRQ_TYPE_LEVEL_HIGH>,
+				     <AIC_IRQ 681 IRQ_TYPE_LEVEL_HIGH>,
+				     <AIC_IRQ 682 IRQ_TYPE_LEVEL_HIGH>,
+				     <AIC_IRQ 683 IRQ_TYPE_LEVEL_HIGH>,
+				     <AIC_IRQ 684 IRQ_TYPE_LEVEL_HIGH>,
+				     <AIC_IRQ 685 IRQ_TYPE_LEVEL_HIGH>;
+			interrupt-names = "mbox0", "mbox1", "mbox2", "mbox3",
+					  "flag0", "flag1", "piodma";
+			iommus = <&avd_dart 0>, <&avd_dart 1>;
+			power-domains = <&ps_avd_sys>;
+			resets = <&ps_avd_sys>;
+			dma-coherent;
+		};
+
 		i2c0: i2c@2a1010000 {
 			compatible = "apple,t8122-i2c", "apple,t8103-i2c";
 			reg = <0x2 0xa1010000 0x0 0x4000>;
Signature · 1 line
2.56.0
#24 lore raw

Re: [PATCH v4 13/17] arm64: dts: apple: t8122: add avd nodes

Thank you for your contribution! Sashiko AI review found 6 potential issues to consider: - [Critical] media: apple: avd: tile dimension underflow in compute_tiles_non_uniform() - [Critical] media…

Thank you for your contribution! Sashiko AI review found 6 potential issues to consider:
- [Critical] media: apple: avd: tile dimension underflow in compute_tiles_non_uniform()
- [Critical] media: apple: avd: out-of-bounds access and div-by-zero in AV1 and H264
- [High] media: apple: avd: unsynchronized reset in avd_watchdog_func() vs IRQ
- [Medium] media: apple: avd: wrong plane length field in stream_slice_mv()
- [Low] arm64: dts: apple: t8122: undocumented apple,t8122-dart compatible string
- [Low] arm64: dts: apple: t8122: undocumented dma-coherent property on video-codec
--

commit 573c860e172e49f12afc5a250236593df08daaa0
Author: Sofus Forstreuter <[email protected]>

arm64: dts: apple: t8122: add avd nodes

This commit adds the avd_dart IOMMU and video-codec Devicetree nodes to enable the Apple Video Decoder on the Apple T8122 SoC.

arch/arm64/boot/dts/apple/t8122.dtsi soc { · line 194

Quoted 10 lines
arch/arm64/boot/dts/apple/t8122.dtsi +2 -0
index 52257fa226317..5f73ad9b247ef 100644
@@ -190,6 +190,39 @@ soc {
 		nonposted-mmio;
 		#size-cells = <2>;
 
+		avd_dart: iommu@289010000 {
+			compatible = "apple,t8122-dart", "apple,t8110-dart";

[Severity: Low]
Should "apple,t8122-dart" be documented in Documentation/devicetree/bindings/iommu/apple,dart.yaml? Without a binding update, make dtbs_check fails schema validation on t8122 targets.

arch/arm64/boot/dts/apple/t8122.dtsi soc { · line 203

Quoted 9 lines
arch/arm64/boot/dts/apple/t8122.dtsi +9 -0
+			reg = <0x2 0x89010000 0x0 0x4000>;
+			interrupt-parent = <&aic>;
+			interrupts = <AIC_IRQ 686 IRQ_TYPE_LEVEL_HIGH>;
+			#iommu-cells = <1>;
+			power-domains = <&ps_avd_sys>;
+		};
+
+		video-codec@289070000 {
+			compatible = "apple,t8122-avd";

[Severity: Critical]
Enabling "apple,t8122-avd" exposes HEVC decoding to userspace, but can compute_tiles_non_uniform() underflow column_width[] and row_height[] and walk off the end of the tile arrays on the kernel heap?

drivers/media/platform/apple/avd/avd-hevc.c:compute_tiles_non_uniform() {
	for (i = 0; i < num_cols - 1; i++) {
		column_width[i] = pps->column_width_minus1[i] + 1;
		sum += column_width[i];
	}
	column_width[i] = pic_in_cts_width - sum;
}

When userspace submits a V4L2_CID_STATELESS_HEVC_PPS control with V4L2_HEVC_PPS_FLAG_TILES_ENABLED set and V4L2_HEVC_PPS_FLAG_UNIFORM_SPACING clear, nothing checks that sum stays below pic_in_cts_width or pic_in_cts_height. If sum exceeds the picture dimension in CTBs, the trailing u16 width or height wraps up to 65535, and compute_tile_ids() reads ctb_addr_rs_to_ts[] and writes tile_ids[] out of bounds on the kernel heap.

In addition, avd_hevc_validate_sps() does not reject zero pic_width_in_luma_samples or pic_height_in_luma_samples (which causes avd_hevc_compute_tiles() to allocate zero-sized buffers and dereference ZERO_SIZE_PTR in compute_tile_ids()) and does not bound log2_min_luma_coding_block_size_minus3 or log2_diff_max_min_luma_coding_block_size before avd_hevc_compute_tiles() shifts 1 by their sum and divides by max_cu_width.

[Severity: Critical]
This node also enables AV1 (for the first time in the series) and H264 on T8122, but can an unvalidated V4L2_CID_STATELESS_AV1_FRAME control underflow the capture buffer offsets in avd_av1_set_prob() and avd_av1_run_preamble()?

drivers/media/platform/apple/avd/avd-av1.c:avd_av1_set_prob() {
	memcpy(vaddr + AVD_AV1_CDFS_OFFSET(length, dst->av1.color_size),
	       av1_ctx->bufs.probs.cpu, sizeof(struct avd_av1_cdfs));
}

frame_width_minus_1 and frame_height_minus_1 are not checked against ctx->decoded_fmt or planes[0].length, so a frame whose computed color_size exceeds length underflows AVD_AV1_CDFS_OFFSET() and AVD_AV1_COLOR_OFFSET(), writing sizeof(struct avd_av1_cdfs) bytes before vaddr in kernel memory. Similarly, avd_h264_validate_sps() does not check SPS macroblock dimensions against ctx->coded_fmt used to size the scratch and auxiliary buffers.

Two other input checks are missing in drivers/media/platform/apple/avd/avd-av1.c:
set_tiles() stores u32 tile_group->tile_row and tile_col in signed ints before checking >= V4L2_AV1_MAX_TILE_ROWS / COLS (allowing values >= 0x80000000 to index tile_info arrays negatively), and calc_upscale() and set_refs() divide by upscaled_plane_w, width, and height without rejecting upscaled_width == 0 or frame_width_minus_1 / frame_height_minus_1 == U32_MAX.

[Severity: Medium]
In the HEVC backend enabled here, does stream_slice_mv() read the wrong plane length field when computing mv_color_addr?

drivers/media/platform/apple/avd/avd-hevc.c:stream_slice_mv() {
	if (ref_valid) {
		dma_addr_t mv_color_addr = ref->dma.y +
			(ref->base.vb.planes[0].length -
			 mv_color_size(fmt_width(ctx), fmt_height(ctx)));
		pusha(mv_color_addr, "mv_colo", 0);
	}
}

When userspace queues VB2_MEMORY_DMABUF capture buffers with v4l2_plane.length set to 0, __prepare_dmabuf() populates ref->base.vb.vb2_buf.planes[0].length while leaving ref->base.vb.planes[0].length at 0. Subtracting mv_color_size() then underflows in 32-bit unsigned arithmetic and programs an IOVA roughly 4 GB past ref->dma.y ( triggering a DART IOMMU fault) instead of using ref->dma.aux_start as stream_refs() does.

Quoted 9 lines
arch/arm64/boot/dts/apple/t8122.dtsi +9 -0
+			reg = <0x2 0x89070000 0x0 0x4000>,
+			      <0x2 0x89080000 0x0 0x10000>,
+			      <0x2 0x89090000 0x0 0x14000>,
+			      <0x2 0x890a4000 0x0 0x4000>,
+			      <0x2 0x89100000 0x0 0x10000>;
+			reg-names = "piodma", "code", "sram", "mbox", "ctrl";
+			interrupt-parent = <&aic>;
+			interrupts = <AIC_IRQ 679 IRQ_TYPE_LEVEL_HIGH>,
+				     <AIC_IRQ 680 IRQ_TYPE_LEVEL_HIGH>,

arch/arm64/boot/dts/apple/t8122.dtsi soc { · line 222

Quoted 10 lines
arch/arm64/boot/dts/apple/t8122.dtsi +10 -0
+				     <AIC_IRQ 681 IRQ_TYPE_LEVEL_HIGH>,
+				     <AIC_IRQ 682 IRQ_TYPE_LEVEL_HIGH>,
+				     <AIC_IRQ 683 IRQ_TYPE_LEVEL_HIGH>,
+				     <AIC_IRQ 684 IRQ_TYPE_LEVEL_HIGH>,
+				     <AIC_IRQ 685 IRQ_TYPE_LEVEL_HIGH>;
+			interrupt-names = "mbox0", "mbox1", "mbox2", "mbox3",
+					  "flag0", "flag1", "piodma";
+			iommus = <&avd_dart 0>, <&avd_dart 1>;
+			power-domains = <&ps_avd_sys>;
+			resets = <&ps_avd_sys>;

[Severity: High]
With mbox0 and resets = <&ps_avd_sys> wired up here, can avd_watchdog_func() reset the ps_avd_sys domain while avd_irq_handler() is concurrently accessing avd->mbox?

CPU0 (kworker) CPU1 (irq/mbox0-avd)
avd_watchdog_func() avd_irq_handler()
writel(0, ...IRQ_ENABLE)
avd_reset(avd)
reset_control_reset()
apple_pmgr_reset_assert()
readl(...MBOX0_RETRIEVE) <-- MMIO in reset
avd_job_finish(ctx, ERROR)
...starts next job,
schedules watchdog_work
cancel_delayed_work(&ctx->watchdog_work)
avd_job_finish(ctx, state) <-- wrong job

avd_watchdog_func() clears AVD_REG_MBOX_IRQ_ENABLE in MMIO but does not call disable_irq() or synchronize with the threaded mbox0 handler before resetting ps_avd_sys and finishing the job. On Apple SoCs, reading avd->mbox while APPLE_PMGR_DEV_DISABLE and APPLE_PMGR_RESET are asserted can trigger an SError, and the racing IRQ thread can cancel the newly scheduled watchdog and finish the next decode job early.

arch/arm64/boot/dts/apple/t8122.dtsi soc { · line 223

Quoted 1 line
arch/arm64/boot/dts/apple/t8122.dtsi +1 -0
+			dma-coherent;

[Severity: Low]
Does Documentation/devicetree/bindings/media/apple,avd.yaml need to allow dma-coherent? The schema specifies additionalProperties: false without listing dma-coherent, causing make dtbs_check to fail on this node.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=13
#25 lore raw

PATCH v4 14/17 arm64: dts: apple: t600x: add avd nodes

In reply to Sofus Forstreuter
---
 arch/arm64/boot/dts/apple/t600x-dieX.dtsi | 33 +++++++++++++++++++++++++++++++
 1 file changed, 33 insertions(+)
arch/arm64/boot/dts/apple/t600x-dieX.dtsi +33 -0
index 7ab60873faf1..77e2772e5a4e 100644
@@ -25,6 +25,39 @@ DIE_NODE(cpufreq_p1): cpufreq@212e20000 {
 		#performance-domain-cells = <0>;
 	};
 
+	DIE_NODE(avd_dart): iommu@287010000 {
+		compatible = "apple,t8110-dart";
+		reg = <0x2 0x87010000 0x0 0x4000>;
+		interrupt-parent = <&aic>;
+		interrupts = <AIC_IRQ DIE_NO 1018 IRQ_TYPE_LEVEL_HIGH>;
+		#iommu-cells = <1>;
+		power-domains = <&DIE_NODE(ps_avd_sys)>;
+	};
+
+	video-codec@287070000 {
+		compatible = "apple,t6000-avd";
+		reg = <0x2 0x87070000 0x0 0x4000>,
+		      <0x2 0x87080000 0x0 0x10000>,
+		      <0x2 0x87090000 0x0 0x10000>,
+		      <0x2 0x870a0000 0x0 0x4000>,
+		      <0x2 0x87100000 0x0 0x10000>;
+		reg-names = "piodma", "code", "sram", "mbox", "ctrl";
+		interrupt-parent = <&aic>;
+		interrupts = <AIC_IRQ DIE_NO 1011 IRQ_TYPE_LEVEL_HIGH>,
+			     <AIC_IRQ DIE_NO 1012 IRQ_TYPE_LEVEL_HIGH>,
+			     <AIC_IRQ DIE_NO 1013 IRQ_TYPE_LEVEL_HIGH>,
+			     <AIC_IRQ DIE_NO 1014 IRQ_TYPE_LEVEL_HIGH>,
+			     <AIC_IRQ DIE_NO 1015 IRQ_TYPE_LEVEL_HIGH>,
+			     <AIC_IRQ DIE_NO 1016 IRQ_TYPE_LEVEL_HIGH>,
+			     <AIC_IRQ DIE_NO 1017 IRQ_TYPE_LEVEL_HIGH>;
+		interrupt-names = "mbox0", "mbox1", "mbox2", "mbox3",
+				  "flag0", "flag1", "piodma";
+		iommus = <&DIE_NODE(avd_dart) 0>, <&DIE_NODE(avd_dart) 1>;
+		power-domains = <&DIE_NODE(ps_avd_sys)>;
+		resets = <&DIE_NODE(ps_avd_sys)>;
+		dma-coherent;
+	};
+
 	DIE_NODE(pmgr): power-management@28e080000 {
 		compatible = "apple,t6000-pmgr", "apple,pmgr", "syscon", "simple-mfd";
 		#address-cells = <1>;
Signature · 1 line
2.56.0
#26 lore raw

Re: [PATCH v4 14/17] arm64: dts: apple: t600x: add avd nodes

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [Medium] arm64: dts: apple: undocumented dma-coherent property on t600x avd node - [Low] arm64: dts: apple…

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [Medium] arm64: dts: apple: undocumented dma-coherent property on t600x avd node
- [Low] arm64: dts: apple: empty commit message body when adding t600x avd nodes
--

commit 1de47f790c19eee753b43e41aaef969640800b84
Author: Sofus Forstreuter <[email protected]>

Quoted 4 lines

arm64: dts: apple: t600x: add avd nodes

[Severity: Low]
This isn't a bug, but the commit message body is empty. Could a short description of the added avd_dart IOMMU and video-codec nodes be included?

Quoted 30 lines
arch/arm64/boot/dts/apple/t600x-dieX.dtsi +22 -0
index 7ab60873faf1e..77e2772e5a4e1 100644
@@ -25,6 +25,39 @@ DIE_NODE(cpufreq_p1): cpufreq@212e20000 {
 		#performance-domain-cells = <0>;
 	};
 
+	DIE_NODE(avd_dart): iommu@287010000 {
+		compatible = "apple,t8110-dart";
+		reg = <0x2 0x87010000 0x0 0x4000>;
+		interrupt-parent = <&aic>;
+		interrupts = <AIC_IRQ DIE_NO 1018 IRQ_TYPE_LEVEL_HIGH>;
+		#iommu-cells = <1>;
+		power-domains = <&DIE_NODE(ps_avd_sys)>;
+	};
+
+	video-codec@287070000 {
+		compatible = "apple,t6000-avd";
+		reg = <0x2 0x87070000 0x0 0x4000>,
+		      <0x2 0x87080000 0x0 0x10000>,
+		      <0x2 0x87090000 0x0 0x10000>,
+		      <0x2 0x870a0000 0x0 0x4000>,
+		      <0x2 0x87100000 0x0 0x10000>;
+		reg-names = "piodma", "code", "sram", "mbox", "ctrl";
+		interrupt-parent = <&aic>;
+		interrupts = <AIC_IRQ DIE_NO 1011 IRQ_TYPE_LEVEL_HIGH>,
+			     <AIC_IRQ DIE_NO 1012 IRQ_TYPE_LEVEL_HIGH>,
+			     <AIC_IRQ DIE_NO 1013 IRQ_TYPE_LEVEL_HIGH>,
+			     <AIC_IRQ DIE_NO 1014 IRQ_TYPE_LEVEL_HIGH>,

arch/arm64/boot/dts/apple/t600x-dieX.dtsi DIE_NODE(cpufreq_p1): cpufreq@212e20000 { · line 59

Quoted 10 lines
arch/arm64/boot/dts/apple/t600x-dieX.dtsi +10 -0
+			     <AIC_IRQ DIE_NO 1015 IRQ_TYPE_LEVEL_HIGH>,
+			     <AIC_IRQ DIE_NO 1016 IRQ_TYPE_LEVEL_HIGH>,
+			     <AIC_IRQ DIE_NO 1017 IRQ_TYPE_LEVEL_HIGH>;
+		interrupt-names = "mbox0", "mbox1", "mbox2", "mbox3",
+				  "flag0", "flag1", "piodma";
+		iommus = <&DIE_NODE(avd_dart) 0>, <&DIE_NODE(avd_dart) 1>;
+		power-domains = <&DIE_NODE(ps_avd_sys)>;
+		resets = <&DIE_NODE(ps_avd_sys)>;
+		dma-coherent;
+	};

[Severity: Medium]
Does adding dma-coherent to video-codec@287070000 fail dtbs_check?

Documentation/devicetree/bindings/media/apple,avd.yaml sets
additionalProperties: false and does not declare dma-coherent, so schema validation rejects this property on all T6000, T6001, and T6002 device trees that include t600x-dieX.dtsi.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=14
#27 lore raw

PATCH v4 15/17 arm64: dts: apple: t602x: add avd nodes

In reply to Sofus Forstreuter
---
 arch/arm64/boot/dts/apple/t602x-dieX.dtsi | 33 +++++++++++++++++++++++++++++++
 1 file changed, 33 insertions(+)
arch/arm64/boot/dts/apple/t602x-dieX.dtsi +33 -0
index 4044c4f21795..3cccf103375c 100644
@@ -24,6 +24,39 @@ DIE_NODE(cpufreq_p1): cpufreq@212e20000 {
 		#performance-domain-cells = <0>;
 	};
 
+	DIE_NODE(avd_dart): iommu@287010000 {
+		compatible = "apple,t6020-dart", "apple,t8110-dart";
+		reg = <0x2 0x87010000 0x0 0x4000>;
+		interrupt-parent = <&aic>;
+		interrupts = <AIC_IRQ DIE_NO 1095 IRQ_TYPE_LEVEL_HIGH>;
+		#iommu-cells = <1>;
+		power-domains = <&DIE_NODE(ps_avd_sys)>;
+	};
+
+	video-codec@287070000 {
+		compatible = "apple,t6020-avd";
+		reg = <0x2 0x87070000 0x0 0x4000>,
+		      <0x2 0x87080000 0x0 0x10000>,
+		      <0x2 0x87090000 0x0 0x10000>,
+		      <0x2 0x870a0000 0x0 0x4000>,
+		      <0x2 0x87100000 0x0 0x10000>;
+		reg-names = "piodma", "code", "sram", "mbox", "ctrl";
+		interrupt-parent = <&aic>;
+		interrupts = <AIC_IRQ DIE_NO 1088 IRQ_TYPE_LEVEL_HIGH>,
+			     <AIC_IRQ DIE_NO 1089 IRQ_TYPE_LEVEL_HIGH>,
+			     <AIC_IRQ DIE_NO 1090 IRQ_TYPE_LEVEL_HIGH>,
+			     <AIC_IRQ DIE_NO 1091 IRQ_TYPE_LEVEL_HIGH>,
+			     <AIC_IRQ DIE_NO 1092 IRQ_TYPE_LEVEL_HIGH>,
+			     <AIC_IRQ DIE_NO 1093 IRQ_TYPE_LEVEL_HIGH>,
+			     <AIC_IRQ DIE_NO 1094 IRQ_TYPE_LEVEL_HIGH>;
+		interrupt-names = "mbox0", "mbox1", "mbox2", "mbox3",
+				  "flag0", "flag1", "piodma";
+		iommus = <&DIE_NODE(avd_dart) 0>, <&DIE_NODE(avd_dart) 1>;
+		power-domains = <&DIE_NODE(ps_avd_sys)>;
+		resets = <&DIE_NODE(ps_avd_sys)>;
+		dma-coherent;
+	};
+
 	DIE_NODE(pmgr): power-management@28e080000 {
 		compatible = "apple,t6020-pmgr", "apple,t8103-pmgr", "syscon", "simple-mfd";
 		#address-cells = <1>;
Signature · 1 line
2.56.0
#28 lore raw

Re: [PATCH v4 15/17] arm64: dts: apple: t602x: add avd nodes

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Low] arm64: dts: apple: undocumented dma-coherent property in t602x avd node --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Low] arm64: dts: apple: undocumented dma-coherent property in t602x avd node
--

commit 7082a27a7eaf587260f0d96194b647ed6fbfb7ed
Author: Sofus Forstreuter <[email protected]>

arm64: dts: apple: t602x: add avd nodes

This commit adds the Apple Video Decoder (AVD) and its associated DART IOMMU device tree nodes for Apple T602x SoCs.

Quoted 30 lines
arch/arm64/boot/dts/apple/t602x-dieX.dtsi +22 -0
index 4044c4f21795f..3cccf103375ca 100644
@@ -24,6 +24,39 @@ DIE_NODE(cpufreq_p1): cpufreq@212e20000 {
 		#performance-domain-cells = <0>;
 	};
 
+	DIE_NODE(avd_dart): iommu@287010000 {
+		compatible = "apple,t6020-dart", "apple,t8110-dart";
+		reg = <0x2 0x87010000 0x0 0x4000>;
+		interrupt-parent = <&aic>;
+		interrupts = <AIC_IRQ DIE_NO 1095 IRQ_TYPE_LEVEL_HIGH>;
+		#iommu-cells = <1>;
+		power-domains = <&DIE_NODE(ps_avd_sys)>;
+	};
+
+	video-codec@287070000 {
+		compatible = "apple,t6020-avd";
+		reg = <0x2 0x87070000 0x0 0x4000>,
+		      <0x2 0x87080000 0x0 0x10000>,
+		      <0x2 0x87090000 0x0 0x10000>,
+		      <0x2 0x870a0000 0x0 0x4000>,
+		      <0x2 0x87100000 0x0 0x10000>;
+		reg-names = "piodma", "code", "sram", "mbox", "ctrl";
+		interrupt-parent = <&aic>;
+		interrupts = <AIC_IRQ DIE_NO 1088 IRQ_TYPE_LEVEL_HIGH>,
+			     <AIC_IRQ DIE_NO 1089 IRQ_TYPE_LEVEL_HIGH>,
+			     <AIC_IRQ DIE_NO 1090 IRQ_TYPE_LEVEL_HIGH>,
+			     <AIC_IRQ DIE_NO 1091 IRQ_TYPE_LEVEL_HIGH>,

arch/arm64/boot/dts/apple/t602x-dieX.dtsi DIE_NODE(cpufreq_p1): cpufreq@212e20000 { · line 58

Quoted 10 lines
arch/arm64/boot/dts/apple/t602x-dieX.dtsi +10 -0
+			     <AIC_IRQ DIE_NO 1092 IRQ_TYPE_LEVEL_HIGH>,
+			     <AIC_IRQ DIE_NO 1093 IRQ_TYPE_LEVEL_HIGH>,
+			     <AIC_IRQ DIE_NO 1094 IRQ_TYPE_LEVEL_HIGH>;
+		interrupt-names = "mbox0", "mbox1", "mbox2", "mbox3",
+				  "flag0", "flag1", "piodma";
+		iommus = <&DIE_NODE(avd_dart) 0>, <&DIE_NODE(avd_dart) 1>;
+		power-domains = <&DIE_NODE(ps_avd_sys)>;
+		resets = <&DIE_NODE(ps_avd_sys)>;
+		dma-coherent;
+	};

[Severity: Low]
Should dma-coherent be dropped from video-codec@287070000 (or added to the binding schema)? Documentation/devicetree/bindings/media/apple,avd.yaml sets
additionalProperties: false without declaring dma-coherent, so dtbs_check fails on the T602x device trees.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=15
#29 lore raw

PATCH v4 16/17 arm64: dts: apple: t6030: add avd nodes

In reply to Sofus Forstreuter
---
 arch/arm64/boot/dts/apple/t6030.dtsi | 33 +++++++++++++++++++++++++++++++++
 1 file changed, 33 insertions(+)
arch/arm64/boot/dts/apple/t6030.dtsi +33 -0
index 524e532830e2..327074092821 100644
@@ -380,6 +380,39 @@ pmgr_gfx: power-management@290e80000 {
 			/* child nodes are added in t6030-pmgr.dtsi */
 		};
 
+		avd_dart: iommu@30b010000 {
+			compatible = "apple,t6030-dart", "apple,t8110-dart";
+			reg = <0x3 0x0b010000 0x0 0x4000>;
+			interrupt-parent = <&aic>;
+			interrupts = <AIC_IRQ 795 IRQ_TYPE_LEVEL_HIGH>;
+			#iommu-cells = <1>;
+			power-domains = <&ps_avd_sys>;
+		};
+
+		video-codec@30b070000 {
+			compatible = "apple,t6030-avd", "apple,t8122-avd";
+			reg = <0x3 0x0b070000 0x0 0x4000>,
+			      <0x3 0x0b080000 0x0 0x10000>,
+			      <0x3 0x0b090000 0x0 0x14000>,
+			      <0x3 0x0b0a4000 0x0 0x4000>,
+			      <0x3 0x0b100000 0x0 0x10000>;
+			reg-names = "piodma", "code", "sram", "mbox", "ctrl";
+			interrupt-parent = <&aic>;
+			interrupts = <AIC_IRQ 788 IRQ_TYPE_LEVEL_HIGH>,
+				     <AIC_IRQ 789 IRQ_TYPE_LEVEL_HIGH>,
+				     <AIC_IRQ 790 IRQ_TYPE_LEVEL_HIGH>,
+				     <AIC_IRQ 791 IRQ_TYPE_LEVEL_HIGH>,
+				     <AIC_IRQ 792 IRQ_TYPE_LEVEL_HIGH>,
+				     <AIC_IRQ 793 IRQ_TYPE_LEVEL_HIGH>,
+				     <AIC_IRQ 794 IRQ_TYPE_LEVEL_HIGH>;
+			interrupt-names = "mbox0", "mbox1", "mbox2", "mbox3",
+					  "flag0", "flag1", "piodma";
+			iommus = <&avd_dart 0>, <&avd_dart 1>;
+			power-domains = <&ps_avd_sys>;
+			resets = <&ps_avd_sys>;
+			dma-coherent;
+		};
+
 		pinctrl_ap: pinctrl@347100000 {
 			compatible = "apple,t6030-pinctrl", "apple,t8103-pinctrl";
 			reg = <0x3 0x47100000 0x0 0x4000>;
Signature · 1 line
2.56.0
#30 lore raw

Re: [PATCH v4 16/17] arm64: dts: apple: t6030: add avd nodes

Thank you for your contribution! Sashiko AI review found 5 potential issues to consider: - [Critical] media: apple: avd: unvalidated AV1 frame dimensions cause OOB write and div-by-0 - [High] media…

Thank you for your contribution! Sashiko AI review found 5 potential issues to consider:
- [Critical] media: apple: avd: unvalidated AV1 frame dimensions cause OOB write and div-by-0
- [High] media: apple: avd: stale job segments and num_alloc in avd_h264_run()
- [High] media: apple: avd: IRQ/watchdog race and unsafe m2m_dev IRQ lifetime
- [Low] arm64: dts: apple: undocumented apple,t6030-dart compatible in t6030.dtsi
- [Low] arm64: dts: apple: undeclared dma-coherent property on video-codec in t6030.dtsi
--

commit 951d171bac144253a801bdaf4450cc32e932132a
Author: Sofus Forstreuter <[email protected]>

arm64: dts: apple: t6030: add avd nodes

This commit adds the Apple Video Decoder (AVD) and its associated DART IOMMU device tree nodes to the T6030 SoC devicetree.

arch/arm64/boot/dts/apple/t6030.dtsi pmgr_gfx: power-management@290e80000 { · line 384

Quoted 10 lines
arch/arm64/boot/dts/apple/t6030.dtsi +2 -0
index 524e532830e20..327074092821c 100644
@@ -380,6 +380,39 @@ pmgr_gfx: power-management@290e80000 {
 			/* child nodes are added in t6030-pmgr.dtsi */
 		};
 
+		avd_dart: iommu@30b010000 {
+			compatible = "apple,t6030-dart", "apple,t8110-dart";

[Severity: Low]
Does "apple,t6030-dart" need to be added to Documentation/devicetree/bindings/iommu/apple,dart.yaml? Without it, dtbs_check fails on T6030 board device trees because compatible only lists apple,t6020-dart paired with apple,t8110-dart.

arch/arm64/boot/dts/apple/t6030.dtsi pmgr_gfx: power-management@290e80000 { · line 393

Quoted 9 lines
arch/arm64/boot/dts/apple/t6030.dtsi +9 -0
+			reg = <0x3 0x0b010000 0x0 0x4000>;
+			interrupt-parent = <&aic>;
+			interrupts = <AIC_IRQ 795 IRQ_TYPE_LEVEL_HIGH>;
+			#iommu-cells = <1>;
+			power-domains = <&ps_avd_sys>;
+		};
+
+		video-codec@30b070000 {
+			compatible = "apple,t6030-avd", "apple,t8122-avd";

[Severity: Critical]
Does enabling the AVD node expose unvalidated AV1 frame dimensions in the AVD driver that allow userspace to trigger a kernel out-of-bounds write or a divide-by-zero panic?

Neither validate_av1_frame() in the V4L2 core nor the AVD driver validates frame->upscaled_width, frame->frame_width_minus_1, or frame->frame_height_minus_1 from V4L2_CID_STATELESS_AV1_FRAME:

drivers/media/platform/apple/avd/avd-av1.c:avd_av1_set_prob() {
    ...
	memcpy(vaddr + AVD_AV1_CDFS_OFFSET(length, dst->av1.color_size),
	       av1_ctx->bufs.probs.cpu, sizeof(struct avd_av1_cdfs));
    ...
}

When userspace submits a frame whose dimensions make dst->av1.color_size larger than the capture buffer length, AVD_AV1_CDFS_OFFSET() underflows and memcpy() writes sizeof(struct avd_av1_cdfs) bytes before vaddr. In addition, calc_upscale() divides by upscaled_plane_w (which is 0 when frame->upscaled_width is 0), and set_refs() divides by frame_width_minus_1 + 1 and frame_height_minus_1 + 1 (which wrap to 0 when set to U32_MAX).

[Severity: High]
Can enabling the AVD node allow userspace to write out of bounds past ctx->job.segments in the H.264 decoder?

When userspace queues a slice with V4L2_BUF_FLAG_M2M_HOLD_CAPTURE_BUF set and then issues VIDIOC_STREAMOFF, avd_h264_stop() frees h264_ctx without clearing ctx->job.segments or resetting ctx->job.num:

drivers/media/platform/apple/avd/avd-h264.c:avd_h264_stop() {
    ...
	kfree(h264_ctx->slices);
	kfree(h264_ctx);

	ctx->priv = NULL;
}

After VIDIOC_STREAMON allocates a fresh h264_ctx with slice_num = 0, queuing slices with first_mb_in_slice != 0 skips avd_init_job() and appends segments at the stale ctx->job.num index without reallocating, writing past the end of ctx->job.buf.cpu. In addition, avd_h264_done() does not reset slice_num or ctx->job.segments on VB2_BUF_STATE_ERROR when V4L2_BUF_FLAG_M2M_HOLD_CAPTURE_BUF is set, and avd_h264_realloc_slices() skips updating job->num_alloc when reusing an existing buffer.

[Severity: High]
Does enabling this device expose a race between avd_watchdog_func() and avd_irq_handler(), as well as an unsafe avd->m2m_dev lifetime across IRQ registration?

kworker <threaded-irq>
avd_watchdog_func()
writel(0, ...MBOX_IRQ_ENABLE)
avd_irq_handler()
avd_reset(avd)
avd_job_finish(ctx, ..._ERROR)
...schedules next job,
re-arms watchdog_work
cancel_delayed_work(&ctx->watchdog_work) avd_job_finish(ctx, state)
<-- corrupts next active job

Because avd_watchdog_func() does not synchronize with the threaded IRQ handler before resetting the hardware and finishing the timed-out job, an in-flight avd_irq_handler() can cancel the newly re-armed watchdog_work and complete the next job prematurely.

Separately, avd_probe() requests the threaded IRQ and boots the firmware (enabling AVD_REG_MBOX_IRQ_ENABLE) before avd_v4l2_init() allocates avd->m2m_dev, and avd_remove() frees avd->m2m_dev before devm unregisters the IRQ, so an interrupt during probe or remove dereferences NULL or freed memory in v4l2_m2m_get_curr_priv(avd->m2m_dev). Finally, avd_boot() loads firmware with relaxed MMIO stores in avd_memcpy_toio() and starts the Cortex-M3 via writel_relaxed(AVD_RUN_CTRL_UNK_RUN, ...) without a write barrier to order the firmware image writes before CPU startup.

Quoted 10 lines
arch/arm64/boot/dts/apple/t6030.dtsi +10 -0
+			reg = <0x3 0x0b070000 0x0 0x4000>,
+			      <0x3 0x0b080000 0x0 0x10000>,
+			      <0x3 0x0b090000 0x0 0x14000>,
+			      <0x3 0x0b0a4000 0x0 0x4000>,
+			      <0x3 0x0b100000 0x0 0x10000>;
+			reg-names = "piodma", "code", "sram", "mbox", "ctrl";
+			interrupt-parent = <&aic>;
+			interrupts = <AIC_IRQ 788 IRQ_TYPE_LEVEL_HIGH>,
+				     <AIC_IRQ 789 IRQ_TYPE_LEVEL_HIGH>,
+				     <AIC_IRQ 790 IRQ_TYPE_LEVEL_HIGH>,

arch/arm64/boot/dts/apple/t6030.dtsi pmgr_gfx: power-management@290e80000 { · line 413

Quoted 10 lines
arch/arm64/boot/dts/apple/t6030.dtsi +10 -0
+				     <AIC_IRQ 791 IRQ_TYPE_LEVEL_HIGH>,
+				     <AIC_IRQ 792 IRQ_TYPE_LEVEL_HIGH>,
+				     <AIC_IRQ 793 IRQ_TYPE_LEVEL_HIGH>,
+				     <AIC_IRQ 794 IRQ_TYPE_LEVEL_HIGH>;
+			interrupt-names = "mbox0", "mbox1", "mbox2", "mbox3",
+					  "flag0", "flag1", "piodma";
+			iommus = <&avd_dart 0>, <&avd_dart 1>;
+			power-domains = <&ps_avd_sys>;
+			resets = <&ps_avd_sys>;
+			dma-coherent;

[Severity: Low]
Should Documentation/devicetree/bindings/media/apple,avd.yaml declare "dma-coherent: true"? Because the binding sets "additionalProperties: false" without listing dma-coherent, dtbs_check rejects this property on video-codec@30b070000.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=16
#31 lore raw

PATCH v4 17/17 arm64: dts: apple: t6031: add avd nodes

In reply to Sofus Forstreuter
---
 arch/arm64/boot/dts/apple/t6031-dieX.dtsi | 33 +++++++++++++++++++++++++++++++
 1 file changed, 33 insertions(+)
arch/arm64/boot/dts/apple/t6031-dieX.dtsi +33 -0
index 1624651c1d92..4fc6d1575b76 100644
@@ -101,6 +101,39 @@ DIE_NODE(pinctrl_ap): pinctrl@2b3000000 {
 		apple,npins = <200>;
 	};
 
+	DIE_NODE(avd_dart): iommu@2cd010000 {
+		compatible = "apple,t6031-dart", "apple,t8110-dart";
+		reg = <0x2 0xcd010000 0x0 0x4000>;
+		interrupt-parent = <&aic>;
+		interrupts = <AIC_IRQ DIE_NO 1192 IRQ_TYPE_LEVEL_HIGH>;
+		#iommu-cells = <1>;
+		power-domains = <&DIE_NODE(ps_avd_sys)>;
+	};
+
+	video-codec@2cd070000 {
+		compatible = "apple,t6031-avd", "apple,t8122-avd";
+		reg = <0x2 0xcd070000 0x0 0x4000>,
+		      <0x2 0xcd080000 0x0 0x10000>,
+		      <0x2 0xcd090000 0x0 0x14000>,
+		      <0x2 0xcd0a4000 0x0 0x4000>,
+		      <0x2 0xcd100000 0x0 0x10000>;
+		reg-names = "piodma", "code", "sram", "mbox", "ctrl";
+		interrupt-parent = <&aic>;
+		interrupts = <AIC_IRQ DIE_NO 1185 IRQ_TYPE_LEVEL_HIGH>,
+			     <AIC_IRQ DIE_NO 1186 IRQ_TYPE_LEVEL_HIGH>,
+			     <AIC_IRQ DIE_NO 1187 IRQ_TYPE_LEVEL_HIGH>,
+			     <AIC_IRQ DIE_NO 1188 IRQ_TYPE_LEVEL_HIGH>,
+			     <AIC_IRQ DIE_NO 1189 IRQ_TYPE_LEVEL_HIGH>,
+			     <AIC_IRQ DIE_NO 1190 IRQ_TYPE_LEVEL_HIGH>,
+			     <AIC_IRQ DIE_NO 1191 IRQ_TYPE_LEVEL_HIGH>;
+		interrupt-names = "mbox0", "mbox1", "mbox2", "mbox3",
+				  "flag0", "flag1", "piodma";
+		iommus = <&DIE_NODE(avd_dart) 0>, <&DIE_NODE(avd_dart) 1>;
+		power-domains = <&DIE_NODE(ps_avd_sys)>;
+		resets = <&DIE_NODE(ps_avd_sys)>;
+		dma-coherent;
+	};
+
 	DIE_NODE(pmgr_gfx): power-management@408e80000 {
 		compatible = "apple,t6031-pmgr", "apple,t8103-pmgr",
 			     "syscon", "simple-mfd";
Signature · 1 line
2.56.0
#32 lore raw

Re: [PATCH v4 17/17] arm64: dts: apple: t6031: add avd nodes

Thank you for your contribution! Sashiko AI review found 4 potential issues to consider: - [Critical] media: apple: avd: out-of-bounds access in compute_tile_ids() on HEVC controls - [High] media…

Thank you for your contribution! Sashiko AI review found 4 potential issues to consider:
- [Critical] media: apple: avd: out-of-bounds access in compute_tile_ids() on HEVC controls
- [High] media: apple: avd: missing dimension checks in avd_av1_set_prob() and calc_upscale()
- [Low] arm64: dts: apple: undocumented apple,t6031-dart compatible in iommu@2cd010000
- [Low] arm64: dts: apple: unpermitted dma-coherent property on video-codec@2cd070000
--

commit 3f6c99ab9326c07d26df77a52366b9ba23343102
Author: Sofus Forstreuter <[email protected]>

arm64: dts: apple: t6031: add avd nodes

This commit adds the Apple Video Decoder (AVD) and its corresponding DART IOMMU nodes to the T6031 per-die devicetree include file.

arch/arm64/boot/dts/apple/t6031-dieX.dtsi DIE_NODE(pinctrl_ap): pinctrl@2b3000000 { · line 105

Quoted 10 lines
arch/arm64/boot/dts/apple/t6031-dieX.dtsi +2 -0
index 1624651c1d92c..4fc6d1575b761 100644
@@ -101,6 +101,39 @@ DIE_NODE(pinctrl_ap): pinctrl@2b3000000 {
 		apple,npins = <200>;
 	};
 
+	DIE_NODE(avd_dart): iommu@2cd010000 {
+		compatible = "apple,t6031-dart", "apple,t8110-dart";

[Severity: Low]
Does apple,t6031-dart need to be documented in Documentation/devicetree/bindings/iommu/apple,dart.yaml first? Without an entry in the binding schema, dtbs_check fails on T6031, T6032, and T6034 device trees.

arch/arm64/boot/dts/apple/t6031-dieX.dtsi DIE_NODE(pinctrl_ap): pinctrl@2b3000000 { · line 114

Quoted 9 lines
arch/arm64/boot/dts/apple/t6031-dieX.dtsi +9 -0
+		reg = <0x2 0xcd010000 0x0 0x4000>;
+		interrupt-parent = <&aic>;
+		interrupts = <AIC_IRQ DIE_NO 1192 IRQ_TYPE_LEVEL_HIGH>;
+		#iommu-cells = <1>;
+		power-domains = <&DIE_NODE(ps_avd_sys)>;
+	};
+
+	video-codec@2cd070000 {
+		compatible = "apple,t6031-avd", "apple,t8122-avd";

[Severity: Critical]
Can enabling the AVD driver on T6031 allow unprivileged userspace with access to /dev/video* to trigger heap out-of-bounds reads and writes in compute_tile_ids() via crafted V4L2_CID_STATELESS_HEVC_SPS and V4L2_CID_STATELESS_HEVC_PPS controls?

drivers/media/platform/apple/avd/avd-hevc.c:compute_tiles_non_uniform() {
	for (i = 0; i < num_cols - 1; i++) {
		column_width[i] = pps->column_width_minus1[i] + 1;
		sum += column_width[i];
	}
	column_width[i] = pic_in_cts_width - sum;

	for (i = 0, sum = 0; i < num_rows - 1; i++) {
		row_height[i] = pps->row_height_minus1[i] + 1;
		sum += row_height[i];
	}
	row_height[i] = pic_in_cts_height - sum;
}

When sum >= pic_in_cts_width or sum >= pic_in_cts_height, subtracting sum underflows u16 column_width[i] or row_height[i] to up to 65535. compute_bd() then produces col_bd and row_bd entries far exceeding the picture CTB dimensions, causing compute_tile_ids() to index
y * pic_in_ctbs_width + x past the end of the heap arrays ctb_addr_rs_to_ts and tile_ids (allocated with pic_in_ctbs_size elements in avd_hevc_compute_tiles()).

In addition, avd_hevc_validate_sps() does not reject zero sps->pic_width_in_luma_samples or sps->pic_height_in_luma_samples (which makes pic_in_ctbs_size == 0 so kzalloc_objs() returns ZERO_SIZE_PTR for ctb_addr_rs_to_ts and tile_ids), nor does it bound sps->log2_min_luma_coding_block_size_minus3 + 3 + sps->log2_diff_max_min_luma_coding_block_size before avd_hevc_compute_tiles() shifts and divides by max_cu_width.

[Severity: High]
Does enabling the AVD driver also expose an out-of-bounds kernel memory write in avd_av1_set_prob() and a division by zero in calc_upscale() when userspace submits crafted V4L2_CID_STATELESS_AV1_FRAME or V4L2_CID_STATELESS_H264_SPS controls?

drivers/media/platform/apple/avd/avd-av1.c:avd_av1_set_prob() {
	...
	memcpy(vaddr + AVD_AV1_CDFS_OFFSET(length, dst->av1.color_size),
	       av1_ctx->bufs.probs.cpu, sizeof(struct avd_av1_cdfs));
}

Neither avd_av1_try_ctrl() nor avd_av1_run_preamble() validates frame->frame_width_minus_1 + 1 and frame->frame_height_minus_1 + 1 against ctx->decoded_fmt.fmt.pix_mp.width and height. When the frame dimensions exceed the capture buffer format dimensions, update_dec_buf_info() computes dst->av1.color_size larger than the plane length, so AVD_AV1_CDFS_OFFSET(length, dst->av1.color_size) underflows and avd_av1_set_prob() writes sizeof(struct avd_av1_cdfs) bytes before vaddr (or wraps width/height to 0 in set_refs() when frame_width_minus_1 == U32_MAX, dividing by zero).

Furthermore, set_header() calls calc_upscale() without checking that frame->upscaled_width is non-zero, dividing by upscaled_plane_w == 0 when frame->upscaled_width == 0. Similarly, avd_h264_validate_sps() does not validate (sps->pic_width_in_mbs_minus1 + 1) * 16 and (sps->pic_height_in_map_units_minus1 + 1) * 16 against the allocated format dimensions before stream_hdr() programs the hardware with the SPS dimensions.

Quoted 11 lines
arch/arm64/boot/dts/apple/t6031-dieX.dtsi +11 -0
+		reg = <0x2 0xcd070000 0x0 0x4000>,
+		      <0x2 0xcd080000 0x0 0x10000>,
+		      <0x2 0xcd090000 0x0 0x14000>,
+		      <0x2 0xcd0a4000 0x0 0x4000>,
+		      <0x2 0xcd100000 0x0 0x10000>;
+		reg-names = "piodma", "code", "sram", "mbox", "ctrl";
+		interrupt-parent = <&aic>;
+		interrupts = <AIC_IRQ DIE_NO 1185 IRQ_TYPE_LEVEL_HIGH>,
+			     <AIC_IRQ DIE_NO 1186 IRQ_TYPE_LEVEL_HIGH>,
+			     <AIC_IRQ DIE_NO 1187 IRQ_TYPE_LEVEL_HIGH>,
+			     <AIC_IRQ DIE_NO 1188 IRQ_TYPE_LEVEL_HIGH>,

arch/arm64/boot/dts/apple/t6031-dieX.dtsi DIE_NODE(pinctrl_ap): pinctrl@2b3000000 { · line 135

Quoted 10 lines
arch/arm64/boot/dts/apple/t6031-dieX.dtsi +10 -0
+			     <AIC_IRQ DIE_NO 1189 IRQ_TYPE_LEVEL_HIGH>,
+			     <AIC_IRQ DIE_NO 1190 IRQ_TYPE_LEVEL_HIGH>,
+			     <AIC_IRQ DIE_NO 1191 IRQ_TYPE_LEVEL_HIGH>;
+		interrupt-names = "mbox0", "mbox1", "mbox2", "mbox3",
+				  "flag0", "flag1", "piodma";
+		iommus = <&DIE_NODE(avd_dart) 0>, <&DIE_NODE(avd_dart) 1>;
+		power-domains = <&DIE_NODE(ps_avd_sys)>;
+		resets = <&DIE_NODE(ps_avd_sys)>;
+		dma-coherent;
+	};

[Severity: Low]
Is dma-coherent allowed by Documentation/devicetree/bindings/media/apple,avd.yaml? That binding sets
additionalProperties: false without listing dma-coherent, which causes dtbs_check to fail on video-codec@2cd070000.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=17