Skip to contentSkip to conversation

media: rockchip: Add JPEG decoder driver

PATCH New Sascha Hauer 2 participants 7 messages Nov 23

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

v8 cover media: rockchip: Add JPEG decoder driver

This series adds support for the Rockchip JPEG decoder hardware. The JPEG decoder is an in-house IP which is integrated into various Rockchip SoCs. The driver is tested on a RK3588 board but reportedly works on RK3568 as well.

An earlier version of this driver was posted as part of the Hantro driver [1]. That turned out to be the wrong abstraction, so it was split up into a series with the Hantro fixes [2] and this series with a standalone driver, which started over at v1.

[1] https://lore.kernel.org/r/[email protected]
[2] https://lore.kernel.org/r/[email protected]

An LLM (Claude) was used throughout the development of this series:
for parts of the driver code, for reviewing it and working through review comments, and for debugging on the hardware and with GStreamer. I have reviewed and tested all of it.

---
Changes in v8:
- Decode 4:2:2 frames to NV16, or to NV12 on request. ENUM_FMT on the
capture queue lists the formats the current frame can decode to
(Philipp)
- Report the coded frame sizes as continuous up to 65535. Frames whose
size is not a multiple of 8, e.g. 1366x768, failed to negotiate in
GStreamer (Philipp)
- Size coded buffers for at least 3 bytes per pixel, also when userspace
asks for less (Sergei)
- Don't resume the m2m queue when runtime PM resume fails (Philipp),
drop a dead error path from suspend
- Use one RKJPEGD_MIN_SIZE for both dimensions, inline
rkjpegd_irq_done() (Philipp)
- Link to v7: https://lore.kernel.org/r/[email protected]

Changes in v7:
- Don't set a capture payload larger than the buffer when a job fails
because the buffer is too small (sashiko)
- Drop the Assisted-by tags, upstream removed them in favour of a
note in the cover letter
- Drop the review questions and answers from the driver patch
- Link to v6: https://lore.kernel.org/r/[email protected]

Changes in v6:
- Rework dynamic resolution change: a changed frame is marked when it
is queued, the decoder stops in front of it, and only the ioctls that
resume change the capture format, so fmt_lock is gone
- Keep a drain going across the capture restart of a resolution change
- Decode grayscale frames to GREY instead of filling the NV12 chroma
plane from the CPU, and allocate capture buffers without a kernel
mapping
- Leave cache maintenance of coded buffers to videobuf2, drop the
dma-buf CPU access calls
- Drop the EOI scan, a truncated frame fails through BUF_EMPTY, and log
all hardware errors
- Drop the runtime PM check in the interrupt handler
- Drop the interrupt masking around the watchdog reset
- Drop the hard reset fallback
- Drop the media device
- Drop the EOS event on STREAMOFF(OUTPUT)
- Allow up to 65535 pixels per side, limited by the size of the decoded
frame instead of 16384 per side
- Report sRGB colorimetry on the capture queue, keep what is set on the
coded queue and default it to V4L2_COLORSPACE_JPEG
- Return a failed frame with its full payload, GStreamer takes an empty
capture buffer for the end of the stream
- Return errors from the header parse instead of setting a flag
- Use guard() and __free(), drop NULL checks the core rules out
- Name the VDPU720 in the Kconfig help
- Use Assisted-by: LLM
- Link to v5: https://lore.kernel.org/r/[email protected]

Changes in v5:
- Keep the device until both the binding and the last file handle are
gone, devres freed it under an open file
- Let a job still running in rkjpegd_remove() finish and start no more,
close() waited forever
- Reset the block after a job that ended in error
- Reset the block after a frame that left SOFT_RST_RDY clear
- Skip trailing padding of any length when looking for the EOI, 63 bytes
of padding hid the marker, and search only the entropy coded data
- Annotate the DMA side buffer as little-endian
- Return -EINVAL from enum_framesizes() for an unsupported format
- Drop most of the in-function comments
- Drop the review note on rkjpegd_remove(), the code is fixed instead
- Bound the Huffman value copy by the table length parsed at queue time
- Fall back to the standard Huffman tables for frames without a DHT
- Resume decoding on V4L2_DEC_CMD_START after a drain or resolution change
- Do not re-arm a drain that already completed
- Report no resolution change for a corrupt frame past the first one
- Send no EOS event for the LAST buffer of a resolution change
- Correct the IRQ clear and Huffman table set comments
- Keep a resolution change out of the mem2mem drain state, a STOP sent
before the capture queue was restarted ended the stream at once
- Look for a mid-stream resolution change only in device_run(), buf_queue()
raced the interrupt handler for the capture buffer
- Set the field on every capture buffer and the sequence on every LAST
buffer the driver returns itself
- Report the first resolution after CREATE_BUFS on the OUTPUT queue too
- Report the capture colorimetry from the OUTPUT format rather than echoing
what userspace passed, and stop S_FMT(CAPTURE) changing the OUTPUT format
- Refuse RGB coded frames, Adobe APP14 transform 0, instead of decoding them
as YCbCr
- Drop the 4:4:0 mode, the JPEG parser never lets such a frame through
- Depend on V4L_MEM2MEM_DRIVERS
- Correct the downstream clock rate in the rk356x DT commit message
- Serialise V4L2_DEC_CMD_STOP/START with the job completion, a drain
racing the last job's interrupt never finished
- Forget a drain that STREAMOFF(CAPTURE) aborted, a later resolution
change re-armed it
- Bracket CPU reads of imported coded buffers with
dma_buf_begin_cpu_access()
- Wait for a running job when probe fails after registering the video
device
- Add an SPDX line to the Makefile
- Link to v4: https://lore.kernel.org/r/[email protected]

Changes in v4:
- Set and read the source change flags under fmt_lock
- Check the runtime PM state in the interrupt handler
- Use dma-buf CPU access around the grayscale chroma fill
- Update the review notes in the driver patch
- Link to v3: https://lore.kernel.org/r/[email protected]

Changes in v3:
- Rename binding to rockchip,rk3568-jpegd.yaml to match the compatible
- Link the earlier Hantro based series in the cover letter
- Enable clocks from the runtime PM callbacks, use pm_ptr()
- Protect capture format and crop with a mutex
- Clear bytesused on capture buffers returned without a picture
- Revert padding the capture buffer to the MCU width, it broke 4:1:1
- Add notes on review questions to the driver patch
- Link to v2: https://lore.kernel.org/r/[email protected]

Changes in v2:
- rename clocks from aclk/hclk to axi/ahb
- Add missing Signed-off-by
- Fix suspend/resume path
- Pad the capture buffer to the mode's MCU width, not to a macroblock
- Reject a frame header picture size outside the supported range
- Set the capture payload at decode time, not at queue time
- Trim comments in the driver
- Link to v1: https://lore.kernel.org/r/[email protected]

---
Sascha Hauer (4):
media: dt-bindings: Add Rockchip JPEG decoder
media: rockchip: Add JPEG decoder driver
arm64: dts: rockchip: rk3588: Add JPEG decoder node
arm64: dts: rockchip: rk356x: Add JPEG decoder node

 .../bindings/media/rockchip,rk3568-jpegd.yaml      |   92 +
 MAINTAINERS                                        |    9 +
 arch/arm64/boot/dts/rockchip/rk356x-base.dtsi      |   22 +
 arch/arm64/boot/dts/rockchip/rk3588-base.dtsi      |   24 +
 drivers/media/platform/rockchip/Kconfig            |    1 +
 drivers/media/platform/rockchip/Makefile           |    1 +
 drivers/media/platform/rockchip/rkjpegd/Kconfig    |   16 +
 drivers/media/platform/rockchip/rkjpegd/Makefile   |    4 +
 .../rockchip/rkjpegd/rkjpegd-vdpu720-regs.h        |  235 ++
 drivers/media/platform/rockchip/rkjpegd/rkjpegd.c  | 2332 ++++++++++++++++++++
 10 files changed, 2736 insertions(+)

---
base-commit: c03c1a14507dfaf8b856c2608f9ac216021fc222
change-id: 20260821-rockchip-jpegdec-0d6880cf656c

Best regards,

Signature · 1 line
Sascha Hauer <[email protected]>
#1 lore raw

PATCH v8 1/4 media: dt-bindings: Add Rockchip JPEG decoder

Add a devicetree binding schema for the JPEG hardware decoder Rockchip integrates into a number of its SoCs. Documents the single register window (task registers plus the LLP link-table block at offset 0x300), the decode interrupt, the AXI and AHB clocks and resets, the IOMMU and the power domain.

The core is not tied to one SoC. Downstream it is known as the VDPU720 and the same block sits on the RK3528, RK3562, RK356x, RK3576, RK3588 and RV1126B, with only the clocks, the resets and the power domain differing, none of which this schema constrains. A compatible per SoC is all it takes to cover them; the RK3568 and the RK3588 are the two that have been tested and are enabled here.

The resets and the power domain are required. The block cannot be reached with its domain off, and the driver takes it out of reset when it probes and puts it back into reset when it is removed.

The IOMMU stays optional. The driver never refers to it, it is a platform integration detail, and rockchip-vpu.yaml does not require it for the other codec blocks on these SoCs either.

---
 .../bindings/media/rockchip,rk3568-jpegd.yaml      | 92 ++++++++++++++++++++++
 MAINTAINERS                                        |  8 ++
 2 files changed, 100 insertions(+)
Documentation/devicetree/bindings/media/rockchip,rk3568-jpegd.yaml new file +92 -0
new file mode 100644
index 0000000000000..27d85f17922ec
@@ -0,0 +1,92 @@
+# SPDX-License-Identifier: (GPL-2.0 OR BSD-2-Clause)
+%YAML 1.2
+---
+$id: http://devicetree.org/schemas/media/rockchip,rk3568-jpegd.yaml#
+$schema: http://devicetree.org/meta-schemas/core.yaml#
+
+title: Rockchip JPEG Decoder
+
+maintainers:
+  - Lucas Sinn <[email protected]>
+  - Sascha Hauer <[email protected]>
+
+description:
+  Rockchip's in-house JPEG/MJPEG hardware decoder, known downstream as the
+  VDPU720.  The same core is integrated into a number of Rockchip SoCs, which
+  differ only in the clocks, resets and power domain they are wired to.  A
+  dedicated Link List Processor (LLP) register block, located at offset 0x300
+  within the same register window, allows the hardware to decode a chain of
+  frames autonomously ("link mode").
+
+properties:
+  compatible:
+    enum:
+      - rockchip,rk3568-jpegd
+      - rockchip,rk3588-jpegd
+
+  reg:
+    maxItems: 1
+    description:
+      The decoder register window.  It covers both the task (function)
+      registers at offset 0x000 and the LLP (link table) registers at
+      offset 0x300.
+
+  interrupts:
+    maxItems: 1
+
+  clocks:
+    items:
+      - description: AXI clock
+      - description: AHB clock
+
+  clock-names:
+    items:
+      - const: axi
+      - const: ahb
+
+  resets:
+    items:
+      - description: AXI reset line
+      - description: AHB reset line
+
+  reset-names:
+    items:
+      - const: axi
+      - const: ahb
+
+  power-domains:
+    maxItems: 1
+
+  iommus:
+    maxItems: 1
+
+required:
+  - compatible
+  - reg
+  - interrupts
+  - clocks
+  - clock-names
+  - resets
+  - reset-names
+  - power-domains
+
+additionalProperties: false
+
+examples:
+  - |
+    #include <dt-bindings/clock/rockchip,rk3588-cru.h>
+    #include <dt-bindings/interrupt-controller/arm-gic.h>
+    #include <dt-bindings/power/rk3588-power.h>
+    #include <dt-bindings/reset/rockchip,rk3588-cru.h>
+
+    video-codec@fdb90000 {
+        compatible = "rockchip,rk3588-jpegd";
+        reg = <0xfdb90000 0x400>;
+        interrupts = <GIC_SPI 129 IRQ_TYPE_LEVEL_HIGH 0>;
+        clocks = <&cru ACLK_JPEG_DECODER>, <&cru HCLK_JPEG_DECODER>;
+        clock-names = "axi", "ahb";
+        resets = <&cru SRST_A_JPEG_DECODER>, <&cru SRST_H_JPEG_DECODER>;
+        reset-names = "axi", "ahb";
+        iommus = <&jpegd_mmu>;
+        power-domains = <&power RK3588_PD_VDPU>;
+    };
MAINTAINERS +8 -0
index 782389bd5cd3d..f47f614dc6857 100644
@@ -23714,6 +23714,14 @@ F:	Documentation/userspace-api/media/v4l/metafmt-rkisp1.rst
 F:	drivers/media/platform/rockchip/rkisp1
 F:	include/uapi/linux/rkisp1-config.h
 
+ROCKCHIP JPEG DECODER DRIVER
+M:	Lucas Sinn <[email protected]>
+M:	Sascha Hauer <[email protected]>
+L:	[email protected]
+L:	[email protected]
+S:	Maintained
+F:	Documentation/devicetree/bindings/media/rockchip,rk3568-jpegd.yaml
+
 ROCKCHIP RK3568 RANDOM NUMBER GENERATOR SUPPORT
 M:	Daniel Golle <[email protected]>
 M:	Aurelien Jarno <[email protected]>
Signature · 1 line
2.47.3
#2 lore raw

Re: [PATCH v8 1/4] media: dt-bindings: Add Rockchip JPEG decoder

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Low] dt-bindings: media: interrupts listed before clocks in rockchip,rk3568-jpegd --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Low] dt-bindings: media: interrupts listed before clocks in rockchip,rk3568-jpegd
--

commit 2a31a76d52b3850d44cf64921cfb2c3b8b1937c3
Author: Sascha Hauer <[email protected]>

media: dt-bindings: Add Rockchip JPEG decoder

This commit adds a devicetree binding schema and MAINTAINERS entry for the Rockchip JPEG hardware decoder on RK3568 and RK3588 SoCs.

Quoted 6 lines
Documentation/devicetree/bindings/media/rockchip,rk3568-jpegd.yaml new file +0 -0
new file mode 100644
index 0000000000000..27d85f17922ec
@@ -0,0 +1,92 @@

[ ... ]

Quoted 12 lines
Documentation/devicetree/bindings/media/rockchip,rk3568-jpegd.yaml new file +12 -0
+  interrupts:
+    maxItems: 1
+
+  clocks:
+    items:
+      - description: AXI clock
+      - description: AHB clock
+
+  clock-names:
+    items:
+      - const: axi
+      - const: ahb

[ ... ]

Quoted 20 lines
Documentation/devicetree/bindings/media/rockchip,rk3568-jpegd.yaml new file +20 -0
+required:
+  - compatible
+  - reg
+  - interrupts
+  - clocks
+  - clock-names
+  - resets
+  - reset-names
+  - power-domains
+
+additionalProperties: false
+
+examples:
+  - |
+    #include <dt-bindings/clock/rockchip,rk3588-cru.h>
+    #include <dt-bindings/interrupt-controller/arm-gic.h>
+    #include <dt-bindings/power/rk3588-power.h>
+    #include <dt-bindings/reset/rockchip,rk3588-cru.h>
+
+    video-codec@fdb90000 {

Documentation/devicetree/bindings/media/rockchip,rk3568-jpegd.yaml line 92

Quoted 10 lines
Documentation/devicetree/bindings/media/rockchip,rk3568-jpegd.yaml new file +10 -0
+        compatible = "rockchip,rk3588-jpegd";
+        reg = <0xfdb90000 0x400>;
+        interrupts = <GIC_SPI 129 IRQ_TYPE_LEVEL_HIGH 0>;
+        clocks = <&cru ACLK_JPEG_DECODER>, <&cru HCLK_JPEG_DECODER>;
+        clock-names = "axi", "ahb";
+        resets = <&cru SRST_A_JPEG_DECODER>, <&cru SRST_H_JPEG_DECODER>;
+        reset-names = "axi", "ahb";
+        iommus = <&jpegd_mmu>;
+        power-domains = <&power RK3588_PD_VDPU>;
+    };

[Severity: Low]
This isn't a bug, but in devicetree binding schemas interrupts should be listed after clocks and clock-names in the properties, required, and examples sections to follow the canonical property ordering.

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

PATCH v8 2/4 media: rockchip: Add JPEG decoder driver

In reply to Sascha Hauer

Add a driver for the JPEG hardware decoder Rockchip integrates into a number of its SoCs. Downstream it is known as the VDPU720, which is the name the register definitions carry here.

Exposes one V4L2 M2M device implementing the stateful decoder interface:
JPEG input -> NV12 output, NV16 for a 4:2:2 frame unless userspace asks for NV12, or GREY for a grayscale frame. The frame
header is parsed on the CPU when a coded buffer is queued. The first buffer queued while the capture queue is stopped sets the capture format and raises V4L2_EVENT_SOURCE_CHANGE, so userspace learns the frame size without parsing the bitstream itself. V4L2_DEC_CMD_STOP drains.

Dynamic resolution change is supported, and has to be for GStreamer:
without V4L2_FMT_FLAG_DYN_RESOLUTION its v4l2videodec does not wait for the initial source change and later takes the pending event for one in the middle of the stream, with the flag it relies on the driver to follow a change. A frame that decodes to another size or pixel format than the one queued before it is marked when it is queued. The decoder stops in front of it, reports the change, returns an empty LAST capture buffer and resumes once userspace has restarted the capture queue or sent V4L2_DEC_CMD_START. The capture format is only ever changed from an ioctl while no job can run.

Hardware requirements:
- a DMA side buffer with Q-tables (zigzag->raster), Huffman mincode and value tables, rebuilt from the frame header on every run
- a two-phase IRQ clear sequence, which some revisions require. It is done unconditionally, see rkjpegd-vdpu720-regs.h
- 16-byte stream alignment with a start-byte offset
- MCU-aligned PIC_H (e.g. 1080p YUV420 needs 1088, not 1080)
- FILL_DOWN_E on every frame, as the reference driver sets it for every NV12 conversion: the vertically subsampled output chroma needs the hardware to complete the bottom of the picture
- DRI (restart interval) support when present

Every address register is a single 32 bit one with no high order companion anywhere in the map, so the DMA masks are capped accordingly. That is no constraint in practice: the block sits behind the Rockchip IOMMU, whose address space is 32 bit wide by construction, and memory above 4GB is reached through it.

A coded buffer that ends before the frame does is left to the hardware:
BUF_EMPTY is enabled for every job and fails it. A capture buffer smaller than the negotiated format fails the job too. A failed frame comes back with the ERROR flag and its full payload. The CPU never touches a capture buffer, so that queue has no kernel mapping.

A job that ends in error, or leaves the block unparked, is followed by an in-block soft reset, and so is a job the watchdog has to end. The interrupt handler decodes the error status registers into a readable diagnostic.

---
 MAINTAINERS                                        |    1 +
 drivers/media/platform/rockchip/Kconfig            |    1 +
 drivers/media/platform/rockchip/Makefile           |    1 +
 drivers/media/platform/rockchip/rkjpegd/Kconfig    |   16 +
 drivers/media/platform/rockchip/rkjpegd/Makefile   |    4 +
 .../rockchip/rkjpegd/rkjpegd-vdpu720-regs.h        |  235 ++
 drivers/media/platform/rockchip/rkjpegd/rkjpegd.c  | 2332 ++++++++++++++++++++
 7 files changed, 2590 insertions(+)
MAINTAINERS +1 -0
index f47f614dc6857..26a5101a6d76d 100644
@@ -23721,6 +23721,7 @@ L:	[email protected]
 L:	[email protected]
 S:	Maintained
 F:	Documentation/devicetree/bindings/media/rockchip,rk3568-jpegd.yaml
+F:	drivers/media/platform/rockchip/rkjpegd/
 
 ROCKCHIP RK3568 RANDOM NUMBER GENERATOR SUPPORT
 M:	Daniel Golle <[email protected]>
drivers/media/platform/rockchip/Kconfig +1 -0
index ba401d32f01ba..53d28eb89e472 100644
@@ -5,4 +5,5 @@ comment "Rockchip media platform drivers"
 source "drivers/media/platform/rockchip/rga/Kconfig"
 source "drivers/media/platform/rockchip/rkcif/Kconfig"
 source "drivers/media/platform/rockchip/rkisp1/Kconfig"
+source "drivers/media/platform/rockchip/rkjpegd/Kconfig"
 source "drivers/media/platform/rockchip/rkvdec/Kconfig"
drivers/media/platform/rockchip/Makefile +1 -0
index 0e0b2cbbd4bd2..c256c51ced269 100644
@@ -2,4 +2,5 @@
 obj-y += rga/
 obj-y += rkcif/
 obj-y += rkisp1/
+obj-y += rkjpegd/
 obj-y += rkvdec/
drivers/media/platform/rockchip/rkjpegd/Kconfig new file +16 -0
new file mode 100644
index 0000000000000..4c269d4a6654e
@@ -0,0 +1,16 @@
+# SPDX-License-Identifier: GPL-2.0
+config VIDEO_ROCKCHIP_JPEGD
+	tristate "Rockchip JPEG decoder driver"
+	depends on V4L_MEM2MEM_DRIVERS
+	depends on ARCH_ROCKCHIP || COMPILE_TEST
+	depends on VIDEO_DEV
+	depends on PM
+	select V4L2_JPEG_HELPER
+	select V4L2_MEM2MEM_DEV
+	select VIDEOBUF2_DMA_CONTIG
+	help
+	  Support for the VDPU720 JPEG decoder found on Rockchip SoCs such
+	  as the RK3568 and RK3588, decoding JPEG and MJPEG frames to NV12,
+	  or to GREY for grayscale frames.
+	  To compile this driver as a module, choose M here: the module
+	  will be called rockchip-jpegd.
drivers/media/platform/rockchip/rkjpegd/Makefile new file +4 -0
new file mode 100644
index 0000000000000..0acf2e6ac6785
@@ -0,0 +1,4 @@
+# SPDX-License-Identifier: GPL-2.0
+obj-$(CONFIG_VIDEO_ROCKCHIP_JPEGD) += rockchip-jpegd.o
+
+rockchip-jpegd-y += rkjpegd.o
drivers/media/platform/rockchip/rkjpegd/rkjpegd-vdpu720-regs.h new file +235 -0

235 lines not on this page · raw message

drivers/media/platform/rockchip/rkjpegd/rkjpegd.c new file +2332 -0

2,332 lines not on this page · raw message

Signature · 1 line
2.47.3
#4 lore raw
Thank you for your contribution! Sashiko AI review found 6 potential issues to consider: - [High] media: rockchip: rkjpegd: race and early flag clear in rkjpegd_stop_at_change() - [High] media…

Thank you for your contribution! Sashiko AI review found 6 potential issues to consider:
- [High] media: rockchip: rkjpegd: race and early flag clear in rkjpegd_stop_at_change()
- [High] media: rockchip: rkjpegd: missing vdev_lock and work sync in rkjpegd_suspend()
- [High] media: rockchip: rkjpegd: race between rkjpegd_watchdog() and rkjpegd_vdpu720_irq()
- [Medium] media: rockchip: rkjpegd: missing EOS event in rkjpegd_stop_streaming()
- [Medium] media: rockchip: rkjpegd: stale draining state across stream stop
- [Medium] media: rockchip: rkjpegd: rkjpegd_track_fmt() clobbers negotiated format
--

commit b2f1b48c77bd5e7b91c91e6a3d7b73159e4ded9c
Author: Sascha Hauer <[email protected]>

media: rockchip: Add JPEG decoder driver

This commit adds a V4L2 M2M stateful JPEG decoder driver for the Rockchip VDPU720 hardware block found on SoCs such as the RK3568 and RK3588.

Quoted 5 lines
drivers/media/platform/rockchip/rkjpegd/rkjpegd.c new file +0 -0
new file mode 100644
index 0000000000000..21cc08c0d4672

[ ... ]

Quoted 73 lines
drivers/media/platform/rockchip/rkjpegd/rkjpegd.c new file +73 -0
+static irqreturn_t rkjpegd_vdpu720_irq(int irq, void *dev_id)
+{
+	struct rkjpegd_dev *jpegd = dev_id;
+	enum vb2_buffer_state state;
+	u32 status;
+
+	status = rkjpegd_read(jpegd, VDPU720_REG_INT);
+
+	/* First phase of the IRQ clear, see VDPU720_IRQ_CLR_KEEP. */
+	rkjpegd_write(jpegd, status & VDPU720_IRQ_CLR_KEEP, VDPU720_REG_INT);
+
+	if (!(status & VDPU720_IRQ_RAW))
+		return IRQ_NONE;
+
+	rkjpegd_write(jpegd, 0, VDPU720_REG_INT);
+
+	state = (status & VDPU720_ERR_MASK) ?
+		VB2_BUF_STATE_ERROR : VB2_BUF_STATE_DONE;
+
+	/*
+	 * A block that did not park itself wedges on the next frame, and a
+	 * clean frame can leave it unparked too, as SOFT_RST_RDY shows.  The
+	 * reset sleeps, so leave it to rkjpegd_vdpu720_run().  The next job
+	 * is only started after job_spinlock has released this one, which
+	 * orders the store.
+	 */
+	if (state == VB2_BUF_STATE_ERROR || !(status & VDPU720_SOFT_RST_RDY))
+		jpegd->needs_reset = true;
+
+	if (status & VDPU720_DEC_ERR) {
+		u32 mcu_pos  = rkjpegd_read(jpegd, VDPU720_REG_DBG_MCU_POS);
+		u32 err_info = rkjpegd_read(jpegd, VDPU720_REG_DBG_ERROR);
+
+		dev_warn_ratelimited(jpegd->dev,
+				     "decode error: MCU pos=(%u,%u) flags=0x%04x [%s%s%s%s%s%s%s%s%s%s] first_idx=%u\n",
+				     (u32)FIELD_GET(VDPU720_DBG_MCU_POS_X, mcu_pos),
+				     (u32)FIELD_GET(VDPU720_DBG_MCU_POS_Y, mcu_pos),
+				     (u32)FIELD_GET(VDPU720_DERR_FLAGS, err_info),
+				     (err_info & VDPU720_DERR_DRI_SEQ)     ? "dri_seq "    : "",
+				     (err_info & VDPU720_DERR_STREAM_FFFF) ? "ffff "       : "",
+				     (err_info & VDPU720_DERR_OTHER_MARK)  ? "bad_mark "   : "",
+				     (err_info & VDPU720_DERR_MCU_CNT_L)   ? "dri_early "  : "",
+				     (err_info & VDPU720_DERR_MCU_CNT_M)   ? "dri_late "   : "",
+				     (err_info & VDPU720_DERR_EOI_NO_END)  ? "eoi_early "  : "",
+				     (err_info & VDPU720_DERR_END_NO_EOI)  ? "no_eoi "     : "",
+				     (err_info & VDPU720_DERR_OVERFLOW)    ? "overflow "   : "",
+				     (err_info & VDPU720_DERR_HUFF_EMPTY)  ? "huff_empty " : "",
+				     (err_info & (VDPU720_DERR_STREAM_R0 |
+						  VDPU720_DERR_STREAM_R1)) ? "stream_mark " : "",
+				     (u32)FIELD_GET(VDPU720_DERR_FIRST_IDX, err_info));
+
+		rkjpegd_write(jpegd, err_info, VDPU720_REG_DBG_ERROR);
+	} else if (state == VB2_BUF_STATE_ERROR) {
+		dev_warn_ratelimited(jpegd->dev, "decode error: status 0x%08x\n",
+				     status);
+	}
+
+	/* A pending watchdog means a job is running, see rkjpegd_watchdog(). */
+	if (cancel_delayed_work(&jpegd->watchdog_work))
+		rkjpegd_job_finish(v4l2_m2m_get_curr_priv(jpegd->m2m_dev),
+				   state);
+
+	return IRQ_HANDLED;
+}
+
+/*
+ * The block ends a stalled job itself, TIMEOUT_E raises an interrupt after
+ * 2^24 idle cycles.  This only fires for a block that stopped answering
+ * altogether, whose interrupt will not come now either.
+ */
+static void rkjpegd_watchdog(struct work_struct *work)
+{
+	struct rkjpegd_dev *jpegd = container_of(to_delayed_work(work),

drivers/media/platform/rockchip/rkjpegd/rkjpegd.c line 1593

Quoted 10 lines
drivers/media/platform/rockchip/rkjpegd/rkjpegd.c new file +10 -0
+						 struct rkjpegd_dev,
+						 watchdog_work);
+	/* Only armed while a job runs, so there is always a context. */
+	struct rkjpegd_ctx *ctx = v4l2_m2m_get_curr_priv(jpegd->m2m_dev);
+
+	dev_err(jpegd->dev, "frame processing timed out\n");
+
+	rkjpegd_vdpu720_reset(ctx);
+	rkjpegd_job_finish(ctx, VB2_BUF_STATE_ERROR);
+}

[Severity: High]
Can rkjpegd_watchdog() and rkjpegd_vdpu720_irq() race when the watchdog expires around the same time an interrupt fires?

Once the workqueue dequeues watchdog_work, cancel_delayed_work() in rkjpegd_vdpu720_irq() returns false without waiting for rkjpegd_watchdog(), and nothing serializes the two paths:

CPU0 (<hardirq>) CPU1 (kworker)
rkjpegd_vdpu720_irq() rkjpegd_watchdog()
/* job 1 IRQ */ rkjpegd_vdpu720_reset()
dev_warn_ratelimited(...) rkjpegd_job_finish() /* job 1 */

                                      ...
                                      rkjpegd_vdpu720_run() /* job 2 */
                                        rkjpegd_arm_watchdog()
  cancel_delayed_work(...)
    /* cancels job 2's watchdog */
  rkjpegd_job_finish()
    /* completes job 2 during DMA */

In addition, if rkjpegd_vdpu720_irq() runs while vdpu720_soft_reset() is polling VDPU720_REG_INT, the interrupt handler writes 0 to VDPU720_REG_INT (clearing VDPU720_SOFT_RST_EN) and sets jpegd->needs_reset = true, after which rkjpegd_vdpu720_reset() times out and overwrites jpegd->needs_reset = false.

Quoted 20 lines
drivers/media/platform/rockchip/rkjpegd/rkjpegd.c new file +20 -0
+
+/**
+ * rkjpegd_track_fmt() - find where the capture format changes
+ * @ctx:	context the coded buffer belongs to
+ * @src_buf:	coded buffer being queued
+ *
+ * The first frame queued while the capture queue is stopped sets the capture
+ * format and reports it.  A refused one has no format, but an application
+ * waits for the event either way, so it gets it for the format as it stands.
+ * A later frame that decodes to another format is marked, and the decoder
+ * stops in front of it, see rkjpegd_stop_at_change().
+ */
+static void rkjpegd_track_fmt(struct rkjpegd_ctx *ctx,
+			      struct rkjpegd_src_buf *src_buf)
+{
+	const struct v4l2_jpeg_header *hdr = &src_buf->header;
+	struct v4l2_m2m_ctx *m2m_ctx = ctx->fh.m2m_ctx;
+	u32 pixelformat;
+
+	src_buf->fmt_change = false;

drivers/media/platform/rockchip/rkjpegd/rkjpegd.c line 1623

Quoted 10 lines
drivers/media/platform/rockchip/rkjpegd/rkjpegd.c new file +10 -0
+
+	if (!vb2_is_streaming(v4l2_m2m_get_dst_vq(m2m_ctx)) &&
+	    !v4l2_m2m_num_src_bufs_ready(m2m_ctx)) {
+		if (!src_buf->parse_error) {
+			rkjpegd_set_hdr_fmt(ctx, hdr);
+			rkjpegd_reset_queued(ctx);
+		}
+		v4l2_event_queue_fh(&ctx->fh, &rkjpegd_src_change_event);
+		return;
+	}

[Severity: Medium]
Does this branch reset ctx->dst_fmt and ctx->convert even when ctx->hdr_known is already true and the format has not changed?

If userspace negotiates V4L2_PIX_FMT_NV12 for a 4:2:2 stream (setting ctx->convert = true and allocating NV12 capture buffers) and later stops and restarts streaming when no output buffers are ready, queuing the next 4:2:2 output buffer enters this branch. rkjpegd_set_hdr_fmt() then resets ctx->convert = false and overwrites ctx->dst_fmt back to V4L2_PIX_FMT_NV16, causing rkjpegd_buf_prepare() to reject the already-allocated NV12 capture buffers with -EINVAL and queuing a spurious V4L2_EVENT_SOURCE_CHANGE.

[ ... ]

drivers/media/platform/rockchip/rkjpegd/rkjpegd.c line 1658

Quoted 13 lines
drivers/media/platform/rockchip/rkjpegd/rkjpegd.c new file +13 -0
+static void rkjpegd_stop_at_change(struct rkjpegd_ctx *ctx,
+				   struct vb2_v4l2_buffer *dst)
+{
+	struct v4l2_m2m_ctx *m2m_ctx = ctx->fh.m2m_ctx;
+
+	/* Set before the event, so that a query after it sees the change. */
+	WRITE_ONCE(ctx->stopped_at_change, true);
+	v4l2_event_queue_fh(&ctx->fh, &rkjpegd_src_change_event);
+
+	v4l2_m2m_dst_buf_remove(m2m_ctx);
+	rkjpegd_last_buffer_done(ctx, dst);
+	v4l2_m2m_job_finish(ctx->dev->m2m_dev, m2m_ctx);
+}

[Severity: High]
Can rkjpegd_stop_at_change() race with rkjpegd_decoder_cmd() when rkjpegd_device_run() runs from m2m_dev->job_work without jpegd->vdev_lock?

When a previous frame finishes in rkjpegd_vdpu720_irq(), v4l2_m2m_buf_done_and_job_finish() schedules m2m_dev->job_work, which invokes rkjpegd_device_run() -> rkjpegd_stop_at_change() without holding jpegd->vdev_lock. As soon as stopped_at_change and V4L2_EVENT_SOURCE_CHANGE are published, userspace can issue V4L2_DEC_CMD_START on another CPU before rkjpegd_stop_at_change() finishes:

CPU0 (kworker) CPU1 (ioctl)
rkjpegd_stop_at_change()
stopped_at_change = true
v4l2_event_queue_fh(...)

                                  rkjpegd_decoder_cmd(V4L2_DEC_CMD_START)
                                    rkjpegd_resume_at_change()
                                      src_buf->fmt_change = false
                                      stopped_at_change = false
                                    v4l2_m2m_try_schedule()
                                      /* skipped: TRANS_RUNNING set */

v4l2_m2m_dst_buf_remove()
rkjpegd_last_buffer_done() <-- completes dst as V4L2_BUF_FLAG_LAST
after resume
v4l2_m2m_job_finish()

Separately, calling vb2_clear_last_buffer_dequeued() in rkjpegd_decoder_cmd() (or in rkjpegd_stop_streaming() on the output queue) before userspace has dequeued that V4L2_BUF_FLAG_LAST buffer from done_list clears last_buffer_dequeued while it is still false; when userspace later dequeues the V4L2_BUF_FLAG_LAST buffer, vb2_dqbuf() sets last_buffer_dequeued = true and fails all subsequent capture dequeues with -EPIPE.

[ ... ]

Quoted 5 lines
drivers/media/platform/rockchip/rkjpegd/rkjpegd.c new file +5 -0
+	if (V4L2_TYPE_IS_OUTPUT(vq->type)) {
+		/* A seek aborts a format change, decoding goes on as before. */
+		if (ctx->stopped_at_change) {
+			WRITE_ONCE(ctx->stopped_at_change, false);
+			vb2_clear_last_buffer_dequeued(&ctx->fh.m2m_ctx->cap_q_ctx.q);

drivers/media/platform/rockchip/rkjpegd/rkjpegd.c line 1956

Quoted 10 lines
drivers/media/platform/rockchip/rkjpegd/rkjpegd.c new file +10 -0
+		}
+		rkjpegd_reset_queued(ctx);
+	} else if (ctx->stopped_at_change) {
+		/*
+		 * Part of the format change, which does not abort a drain:
+		 * dev-decoder.rst has the drain go on once it is handled.
+		 */
+		rkjpegd_resume_at_change(ctx);
+		return;
+	}

[Severity: Medium]
Can returning early here without calling v4l2_m2m_update_stop_streaming_state() leave m2m_ctx->is_draining and m2m_ctx->next_buf_last stuck at true when both queues are stopped?

If a drain is active when the decoder stops at a format change and userspace stops the capture queue first, this branch clears ctx->stopped_at_change and skips v4l2_m2m_update_stop_streaming_state(), leaving m2m_ctx->is_draining set while the capture queue is not streaming (the same state can be reached if V4L2_DEC_CMD_STOP is called in rkjpegd_decoder_cmd() while the capture queue is not streaming). If userspace then stops the output queue as well, v4l2_m2m_update_stop_streaming_state() on the output queue sees is_draining == true with no ready capture buffer and sets m2m_ctx->next_buf_last = true. When streaming is later restarted, the first capture buffer queued in rkjpegd_buf_queue() hits v4l2_m2m_dst_buf_is_last() and terminates the new stream immediately.

drivers/media/platform/rockchip/rkjpegd/rkjpegd.c line 1959

Quoted 3 lines
drivers/media/platform/rockchip/rkjpegd/rkjpegd.c new file +3 -0
+
+	v4l2_m2m_update_stop_streaming_state(ctx->fh.m2m_ctx, vq);
+}

[Severity: Medium]
Should rkjpegd_stop_streaming() queue rkjpegd_eos_event when v4l2_m2m_update_stop_streaming_state() marks the decoder stopped?

When the output queue stops streaming while a drain is in progress and a capture buffer is already on rdy_queue, v4l2_m2m_update_stop_streaming_state() completes that capture buffer with V4L2_BUF_FLAG_LAST and sets m2m_ctx->has_stopped = true, so rkjpegd_buf_queue() will not run later to queue V4L2_EVENT_EOS.

[ ... ]

drivers/media/platform/rockchip/rkjpegd/rkjpegd.c line 2291

Quoted 9 lines
drivers/media/platform/rockchip/rkjpegd/rkjpegd.c new file +9 -0
+/* pm_runtime_force_suspend() ignores the usage count, let the job finish. */
+static int rkjpegd_suspend(struct device *dev)
+{
+	struct rkjpegd_dev *jpegd = dev_get_drvdata(dev);
+
+	v4l2_m2m_suspend(jpegd->m2m_dev);
+
+	return pm_runtime_force_suspend(dev);
+}

[Severity: High]
Does rkjpegd_suspend() need jpegd->vdev_lock around v4l2_m2m_suspend() and cancel_delayed_work_sync(&jpegd->watchdog_work) before pm_runtime_force_suspend(), as rkjpegd_vdev_unregister() does?

v4l2_m2m_suspend() reads m2m_dev->curr_ctx under job_spinlock, drops the spinlock, and waits on curr_ctx->finished. Without jpegd->vdev_lock, a concurrent rkjpegd_release() (for example from delayed_fput_work) can free m2m_ctx while v4l2_m2m_suspend() is about to wait on it:

CPU0 CPU1
rkjpegd_suspend() rkjpegd_release()
v4l2_m2m_suspend()

    curr_ctx = m2m_dev->curr_ctx
                                    mutex_lock(&jpegd->vdev_lock)
                                    v4l2_m2m_ctx_release(m2m_ctx)
                                      kfree(m2m_ctx)
    wait_event(curr_ctx->finished, ...)
                                  <-- use-after-free

Without cancel_delayed_work_sync(&jpegd->watchdog_work), an in-flight rkjpegd_watchdog() can also touch device registers after pm_runtime_force_suspend() disables the clocks.

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

PATCH v8 3/4 arm64: dts: rockchip: rk3588: Add JPEG decoder node

In reply to Sascha Hauer

Add device tree nodes for the Rockchip JPEG hardware decoder and its IOMMU on the RK3588.

The decoder is at 0xfdb90000 with its MMU at 0xfdb90480. It takes the AXI and AHB clocks and resets, and sits in the VDPU power domain. The AXI clock is pinned to 600 MHz, which is the rate the downstream BSP runs it at; it is a dedicated clock, not shared with another block.

Both blocks are entirely on-SoC and have no board dependency, so they are enabled unconditionally like the other codec blocks in this file.

---
 arch/arm64/boot/dts/rockchip/rk3588-base.dtsi | 24 ++++++++++++++++++++++++
 1 file changed, 24 insertions(+)
arch/arm64/boot/dts/rockchip/rk3588-base.dtsi +24 -0
index 376ad04e07869..cc53878502898 100644
@@ -1317,6 +1317,30 @@ rga: rga@fdb80000 {
 		power-domains = <&power RK3588_PD_VDPU>;
 	};
 
+	jpegd: video-codec@fdb90000 {
+		compatible = "rockchip,rk3588-jpegd";
+		reg = <0x0 0xfdb90000 0x0 0x400>;
+		interrupts = <GIC_SPI 129 IRQ_TYPE_LEVEL_HIGH 0>;
+		clocks = <&cru ACLK_JPEG_DECODER>, <&cru HCLK_JPEG_DECODER>;
+		clock-names = "axi", "ahb";
+		assigned-clocks = <&cru ACLK_JPEG_DECODER>;
+		assigned-clock-rates = <600000000>;
+		resets = <&cru SRST_A_JPEG_DECODER>, <&cru SRST_H_JPEG_DECODER>;
+		reset-names = "axi", "ahb";
+		iommus = <&jpegd_mmu>;
+		power-domains = <&power RK3588_PD_VDPU>;
+	};
+
+	jpegd_mmu: iommu@fdb90480 {
+		compatible = "rockchip,rk3588-iommu", "rockchip,rk3568-iommu";
+		reg = <0x0 0xfdb90480 0x0 0x40>;
+		interrupts = <GIC_SPI 130 IRQ_TYPE_LEVEL_HIGH 0>;
+		clocks = <&cru ACLK_JPEG_DECODER>, <&cru HCLK_JPEG_DECODER>;
+		clock-names = "aclk", "iface";
+		power-domains = <&power RK3588_PD_VDPU>;
+		#iommu-cells = <0>;
+	};
+
 	vepu121_0: video-codec@fdba0000 {
 		compatible = "rockchip,rk3588-vepu121";
 		reg = <0x0 0xfdba0000 0x0 0x800>;
Signature · 1 line
2.47.3
#6 lore raw

PATCH v8 4/4 arm64: dts: rockchip: rk356x: Add JPEG decoder node

In reply to Sascha Hauer

Add device tree nodes for the Rockchip JPEG hardware decoder and its IOMMU on the RK356x.

The decoder is the same block as on the RK3588, here at 0xfded0000 with its MMU at 0xfded0480 and the same 0x400 register window. Only the integration differs: ACLK_JDEC and HCLK_JDEC instead of the JPEG decoder clocks, SRST_A_JDEC and SRST_H_JDEC for the AXI and AHB resets, and the RGA power domain rather than VDPU.

No rate is assigned to the AXI clock here. Unlike on the RK3588 it is a gate off aclk_rga_pre, shared with the RGA, the IEP and the EBC, so a rate set for the decoder would move those too. Its mux tops out at 300 MHz, which is also the default rate of the downstream driver. The downstream device tree assigns no rate to it either, and the vepu node on the same clock tree already leaves it alone.

The domain needs nothing else, it already lists qos_jpeg_dec.

Both blocks are entirely on-SoC and have no board dependency, so they are enabled unconditionally like the other codec blocks in this file.

---
 arch/arm64/boot/dts/rockchip/rk356x-base.dtsi | 22 ++++++++++++++++++++++
 1 file changed, 22 insertions(+)
arch/arm64/boot/dts/rockchip/rk356x-base.dtsi +22 -0
index a5832895bd392..e6c7ae908a99f 100644
@@ -619,6 +619,28 @@ rga: rga@fdeb0000 {
 		power-domains = <&power RK3568_PD_RGA>;
 	};
 
+	jpegd: video-codec@fded0000 {
+		compatible = "rockchip,rk3568-jpegd";
+		reg = <0x0 0xfded0000 0x0 0x400>;
+		interrupts = <GIC_SPI 62 IRQ_TYPE_LEVEL_HIGH>;
+		clocks = <&cru ACLK_JDEC>, <&cru HCLK_JDEC>;
+		clock-names = "axi", "ahb";
+		resets = <&cru SRST_A_JDEC>, <&cru SRST_H_JDEC>;
+		reset-names = "axi", "ahb";
+		iommus = <&jpegd_mmu>;
+		power-domains = <&power RK3568_PD_RGA>;
+	};
+
+	jpegd_mmu: iommu@fded0480 {
+		compatible = "rockchip,rk3568-iommu";
+		reg = <0x0 0xfded0480 0x0 0x40>;
+		interrupts = <GIC_SPI 61 IRQ_TYPE_LEVEL_HIGH>;
+		clocks = <&cru ACLK_JDEC>, <&cru HCLK_JDEC>;
+		clock-names = "aclk", "iface";
+		power-domains = <&power RK3568_PD_RGA>;
+		#iommu-cells = <0>;
+	};
+
 	vepu: video-codec@fdee0000 {
 		compatible = "rockchip,rk3568-vepu";
 		reg = <0x0 0xfdee0000 0x0 0x800>;
Signature · 1 line
2.47.3