Skip to content

media: apple: avd: check slice, tile and format parameters against the buffers - #2946

Merged
RyanTheTide merged 27 commits into
integration/aurorafrom
avd/param-bounds
Nov 23, 2026
Merged

RyanTheTide merged 27 commits into
integration/aurorafrom
avd/param-bounds

Conversation

@RyanTheTide

Copy link
Copy Markdown

Stacked on #2945 (it adds the job-table bound and the HEVC tile check that this series builds on).

Problem

Several fields taken from the stateless controls or the bitstream are used as indices or DMA offsets without being checked against what they address:

  • HEVC: slice_segment_addr, the collocated reference index and the DPB entry it selects, and slice and entry point offsets and sizes, none of them checked against the OUTPUT payload.
  • VP9: the tile size walk through the OUTPUT buffer. Header sizes could exceed the payload, sizes could underflow, and the mapping was not checked for NULL.
  • AV1: tile_row and tile_col of the tile-group entries.
  • The run path also read the AV1 tile-group array through the control's storage, which a concurrent VIDIOC_S_EXT_CTRLS can reallocate.

Some sizes the hardware is given were not tied to the buffers it was given:

  • VIDIOC_TRY_FMT(CAPTURE) rewrote the context's compressed reference layout.
  • The H.264 SPS picture size was never compared with the negotiated format.
  • VP9 frames could be larger than the coded format that sizes the scratch.
  • The bit depth and chroma format a job programs come from the current control value, which was only compared with the CAPTURE buffers in s_ctrl. The control framework skips s_ctrl for an unchanged value and for a control of a codec that is not selected.

Per-open and per-stream allocations had no cap: a 12 MiB coherent FIFO on every open(), and an H.264 slice table sized straight from the SPS.

Change

  • HEVC: before building a job, check every slice. Its address must be a CTB of the picture. The collocated index must fit the reference list, and with temporal MV prediction its active part (H.265 7.4.7.1). Each slice segment's data must lie inside the payload, using the same segment layout as the builder. Building also stops if the tile position runs past the boundary tables.
  • VP9: walk the tile sizes with explicit bounds and fail the frame on the first tile that does not fit, including the last one. Refuse a frame larger than the coded format.
  • AV1: refuse tile-group entries whose row or column lies outside the frame's tile grid. Copy the entries under the control lock and check and use the copy, as HEVC already does for its dynamic arrays.
  • TRY_FMT(CAPTURE) computes the layout into a local copy. Only S_FMT(CAPTURE) and the format reset store it.
  • H.264: refuse an SPS larger than the coded format (H.264 7.4.2.1.1). Cap the slice table made at STREAMON at the driver's existing slice limit.
  • When a job is built, derive the picture format from the control value the job uses. Refuse the job unless it is the format the buffers were sized for and the CAPTURE format fits it. H.264 and VP9 also record the bit depth their scratch was sized for at STREAMON, and a job of another depth is refused. H.264 STREAMON reads the SPS's current value, not the last value tried.
  • H.264 and AV1 also build each job from copies of their controls taken under the control lock (HEVC and VP9 do so in the base PR), through one helper that looks the control up before taking the lock.
  • AV1: the upscaled width must lie between the frame width and the CAPTURE width, and equal the frame width when superres is off. VP9 and AV1 also check the frame size against the coded format when the control is set, not only at run time.
  • Do not submit a job when the context has no instruction FIFO.
  • Allocate the context's instruction FIFO at STREAMON(OUTPUT) instead of open(), and free it at STREAMOFF. Charge the H.264 STREAMON allocations to the caller (GFP_KERNEL_ACCOUNT).

Conformant streams are unaffected. A missing reference that a client marks with an index past the DPB (GStreamer uses 0xff) still decodes: HEVC then uses no collocated motion vectors for that slice, instead of reading past the DPB array. No new parameters, gates or tables.

Known limits, left for follow-ups:

  • A PPS with both tiles and wavefront parallel processing whose segments outnumber the tile boundary table (more than 22 rows of segments) is refused. Before, the builder read past that table. HEVC version 1 Main and Main 10 streams cannot enable both tools at once, and the builder never mapped entry points of such streams to tiles correctly.
  • avd_h264_realloc_slices(), avd_init_job() and the per-bank FIFOs still allocate without __GFP_ACCOUNT. They run in the decode worker, so the charge would not reach the caller.

Testing

  • KUnit (arm64 QEMU, KASAN): new suites apple-avd-fmt, apple-avd-v4l2, apple-avd-av1 and the new cases in apple-avd-hevc, apple-avd-vp9 and apple-avd-h264 pass, and so does the rest of the module's KUnit.
  • Each new test fails without its fix. Replacing the AV1 copy with the live pointer gives a KASAN use-after-free in the test.
  • Hardware: M2 (T8112), default cmdline: stock and patched modules give identical output on 9 decode clips and the 1080p/4K bench; malformed parameters are refused without a hang. Details below.

Still to run

  • Rows on an M1-family and an M4-family Mac.

Overlap

#2809, #2136, #2158 and the AVD part of #2755 touch the same format and slice paths; whichever lands first, the others rebase. Before merging #2945, retarget this PR to integration/aurora.

Commits
  1. media: apple: avd: hevc: check slice addresses, references and data
  2. media: apple: avd: vp9: keep the tiles within the bitstream
  3. media: apple: avd: av1: bound tile_row and tile_col of the tile entries
  4. media: apple: avd: Keep TRY_FMT(CAPTURE) from changing the context
  5. media: apple: avd: h264: Check the SPS picture size against the format
  6. media: apple: avd: vp9: refuse frames larger than the coded format
  7. media: apple: avd: check the picture format against the buffers at run time
  8. media: apple: avd: av1: copy the tile-group entries for the run
  9. media: apple: avd: h264: Bound the slice table made at STREAMON
  10. media: apple: avd: Allocate the context FIFO at STREAMON
  11. media: apple: avd: refuse pictures deeper than the scratch was sized for
  12. media: apple: avd: add a helper to copy a control's value for a run
  13. media: apple: avd: h264: use copies of the controls for a run
  14. media: apple: avd: av1: use copies of the controls for a run
  15. media: apple: avd: av1: bound the upscaled width
  16. media: apple: avd: check the VP9 and AV1 frame size when the control is set
  17. media: apple: avd: do not submit without the context FIFO
  18. media: apple: avd: hevc: test entry point offsets that exceed their slice
Test details

KUnit (arm64 QEMU, KASAN, avd-pm.kunitconfig) at this PR head: 167/167 pass. With the fixes reverted and the tests kept, every new test fails (the AV1 live-pointer case with a KASAN use-after-free).

Hardware, M2 (T8112), default boot 7.3.0-aurora-fleet82, default cmdline: the stock apple-avd.ko against a module built from the fleet82 AVD source plus all 23 commits of this stack (same signing key), swapped in user space:

  • 9 decode clips (HEVC tiles uniform and non-uniform, multi-slice, WPP; VP9 tiles; AV1 tiles; H.264 multi-slice and baseline): output md5 identical between stock and patched, and again after the malformed-input cases.
  • avd-bench H.264/HEVC 1080p and 4K, 2 passes: bit-exact on both, throughput unchanged.
  • Malformed slice, tile, size and format parameters: refused with -EINVAL at control set or STREAMON, or failed as an error buffer, no hang; 0 oops/KASAN/DART faults. One follow-up frame with synthetic controls ran into the driver's frame timeout and recovery, which completed in 6 ms; later decodes were unchanged.
  • 64 opens without streaming: MemFree drops by about 1.9 MB (the FIFO is now allocated at STREAMON).

Evidence (our own captures): traces/codec/20261123-avd-tile-bounds-m2.

Assisted-by: LLM (Claude:Opus 5.5)

push() wrote the next instruction into job->segments[job->num] without
checking that the segment exists or has room. The codecs size the table
from the request before building it, so an error in that sizing became a
write past the table, and a segment that filled up wrote into the next
one. avd_open_build_program() only noticed a full segment after the
writes.

Record the number of allocated segments in the job, and have push() drop
an instruction that has no segment or no room and mark the job. A marked
job, or one whose segment index is past the table, is refused with
-EOVERFLOW instead of being turned into a program. The H.264 path, which
grows the table when a picture needs more slices, updates the count.

Add KUnit cases for a full segment and a full table.

Signed-off-by: Ryan Murray <ryan@aurorasilicon.org>
The tile tables are sized from the SPS picture size in CTBs, but explicitly
sized tile columns and rows were taken from the PPS without comparing them
with that size. The last column or row then took a wrapped, very large
width, and building the CTB raster-to-tile-scan and tile id tables wrote
outside both tables.

Before building the tables, require what H.265 7.4.3.3.1 requires: no more
tile columns or rows than the picture has CTBs, and explicit widths and
heights that leave a non-empty last column and row. Also refuse an SPS
with a zero picture width or height, or a CTB size other than 16, 32 or 64
(7.4.3.2.1), which the tables and the slice address arithmetic divide by.
As a second line, the tile id table builder skips any index outside the
tables.

Add KUnit cases for the SPS geometry and tile layout checks that also build
the tables, for accepted and refused layouts.

Signed-off-by: Ryan Murray <ryan@aurorasilicon.org>
The VP9 job is sized with one segment per tile, computed in int from
tile_rows_log2 and tile_cols_log2, and set_tiles() then walks the tile
grid with u32 counts. The V4L2 core bounds tile_cols_log2 to 6 but not
tile_rows_log2, and the driver checked neither, so the int product can
wrap and the job be allocated smaller than the grid that is filled in.

Check the tiling in avd_vp9_validate_frame(), which runs when the frame
control is set and again when the frame runs: tile_rows_log2 is at most
2 and tile_cols_log2 lies between calc_min_log2_tile_cols() and
calc_max_log2_tile_cols() for the frame width (VP9 6.2.13 tile_info()
and 6.2.14). With the 4096-pixel coded width limit that also keeps the
column count within the VP9_MAX_TILE_COLS the scratch is sized for.
Compute the segment count as a size_t shift of the summed log2 values.

Add a KUnit test for the tiling check.

Signed-off-by: Ryan Murray <ryan@aurorasilicon.org>
validate_vp9_frame() checks tile_cols_log2 against its maximum but
accepts any tile_rows_log2. The VP9 tile_info() syntax (section 6.2.13)
codes it as at most two one-bit increments, so it is 0, 1 or 2. Reject
larger values so drivers do not each have to.

Signed-off-by: Ryan Murray <ryan@aurorasilicon.org>
The HEVC and VP9 run paths kept pointers into the current values of the
picture controls (HEVC SPS, PPS, decode parameters and scaling matrix, VP9
frame and compressed header) while they checked those values and then built
the job from them. A VIDIOC_S_EXT_CTRLS that sets current values, not a
request, is not serialized with the decode work, so the values could change
between the checks and their use, and the tile tables and job table could
be built from values that were never checked.

Copy the controls under the control lock when the job starts, as the HEVC
path already does for its slice and entry point arrays, and check and
build from the copies.

Signed-off-by: Ryan Murray <ryan@aurorasilicon.org>
The slice builder indexed the CTB tables with each slice's
slice_segment_addr, the reference list with collocated_ref_idx and the DPB
with the list entry it found there, none of which were compared with the
size of what they index. It also handed the decoder slice and entry point
offsets and sizes without comparing them with the OUTPUT payload, so a
size could underflow or point past the buffer.

Before building the job, check every slice: its address must be a CTB of
the picture, the collocated reference index must fit the reference list
(and, with temporal MV prediction, its active part, H.265 7.4.7.1), the
entry it selects must be a DPB entry, and each slice segment's data must
lie inside the payload, using the same segment layout as the builder. Also
stop building when the tile position runs past the tile boundary tables.

Add KUnit cases for accepted and refused slices.

Signed-off-by: Ryan Murray <ryan@aurorasilicon.org>
set_tiles() takes the tile data offset from the two header sizes of the
frame control and reads the size of every tile but the last from the
OUTPUT buffer, without comparing either with the payload. The remaining
size is a u32 that wraps when the header sizes exceed the payload, and
the "tile_size > size - 4" check wraps when fewer than four bytes are
left, so the walk can read and hand to the decoder offsets and sizes
outside the buffer. The buffer mapping is not checked for NULL either.

Factor the step into avd_vp9_next_tile(): it requires a mapping, the
tile offset within the payload, four bytes for a tile size and the tile
within what is left, all without wrapping, and a non-empty tile (VP9
9.2.1). Every tile handed to the decoder, the last one included, then
lies within the payload. On a bad layout set_tiles() fails the frame
with -EINVAL instead of submitting the tiles it has so far.

Add KUnit tests for the tile walk.

Signed-off-by: Ryan Murray <ryan@aurorasilicon.org>
set_tiles() looks up mi_row_starts[], mi_col_starts[],
height_in_sbs_minus_1[] and width_in_sbs_minus_1[] of the frame's
tile_info with the tile_row and tile_col fields of each tile-group
entry. The control framework does not validate
V4L2_CTRL_TYPE_AV1_TILE_GROUP_ENTRY, and avd_av1_check_tiles() only
checked each tile's offset and size, so values past tile_rows/tile_cols
indexed past the ends of those arrays.

In a conformant stream TileRow < TileRows and TileCol < TileCols
(AV1 5.11.1). Reject a frame whose tile entries are outside the frame's
tile grid, and also check tile_rows and tile_cols against
V4L2_AV1_MAX_TILE_ROWS/COLS in the same place so the helper does not
depend on the core's frame validation for the array sizes.

Make avd_av1_check_tiles() take the tile grid, the entries and the
payload size directly so it can be exercised from KUnit, and add
avd-av1-test.c covering the grid bounds, the entry count and the
offset/size check.

Signed-off-by: Ryan Murray <ryan@aurorasilicon.org>
avd_fill_decoded_pixfmt() stored the compressed reference layout of the
format it was given in ctx->comp. TRY_FMT(CAPTURE) shares it with
S_FMT, so trying a format replaced the layout of the negotiated one,
also while CAPTURE buffers were allocated or streaming. The run path
places the compressed area at ctx->comp.start_offset in each CAPTURE
buffer and hands ctx->comp.offsets to the decoder, so the decoder then
used a layout that did not match the buffers, and the check that lets a
format control change on a busy queue compared against the tried format.

Compute the layout into a caller provided struct avd_comp. TRY_FMT
discards it; ctx->comp is only stored by avd_reset_decoded_fmt() and
avd_s_capture_fmt(), which do not run with CAPTURE buffers allocated,
so ctx->comp always describes ctx->decoded_fmt.

Add KUnit tests that TRY_FMT(CAPTURE) leaves ctx->comp and the decoded
format unchanged, busy or not, and that S_FMT(CAPTURE) stores the layout
of the format it sets.

Signed-off-by: Ryan Murray <ryan@aurorasilicon.org>
The picture size the hardware is programmed with comes from the SPS
(pic_width_in_mbs_minus1, pic_height_in_map_units_minus1), while the
CAPTURE buffers, the compressed reference and motion vector areas in
them, and the per-row scratch are sized from the OUTPUT format.
avd_h264_validate_sps() did not compare the two, so a picture larger
than the negotiated format was decoded into buffers too small for it.

Refuse an SPS whose picture (H.264 7.4.2.1.1: PicWidthInMbs by
FrameHeightInMbs macroblocks) is larger than the OUTPUT format, as the
HEVC SPS check does. S_FMT(OUTPUT) rounds the format up to whole
macroblocks, so a 1920x1080 stream with its 1088 line coded picture
still fits. The check applies when the control is set, at STREAMON and
again when a request's controls are applied at run time.

Add a KUnit test for pictures that fit, including 1080p with the
OUTPUT format set to 1920x1080 or 1920x1088, and for pictures that are
one macroblock or more too large.

Signed-off-by: Ryan Murray <ryan@aurorasilicon.org>
avd_vp9_alloc_bufs() sizes the per-row and per-column scratch (color,
ip_above, lf_above, seg, lf_left, az_left, above_info, ...) at STREAMON
from the OUTPUT format. validate_dec_params() ties the frame size only
to the CAPTURE format, which avd_try_capture_fmt() lets be larger than
the coded size and which can be changed while OUTPUT streams, so a frame
can be larger than the scratch was sized for.

Also require the frame to fit the coded format, which cannot change
while the scratch exists, as HEVC does for its SPS. Clients set the
coded format to the stream size, and the CAPTURE format is at least the
coded size, so conformant streams are not affected.

Add a KUnit test for the size check.

Signed-off-by: Ryan Murray <ryan@aurorasilicon.org>
…n time

The CAPTURE buffers, their compressed reference area and the per-context
scratch are sized for ctx->image_fmt, but each codec programs the bit depth
and chroma format from the current value of its format control (the H.264
or HEVC SPS, the VP9 frame, the AV1 sequence). The two were only compared
in s_ctrl, which the control framework skips for an unchanged value and
which ignores a control of a codec that is not selected, while an OUTPUT
format change resets ctx->image_fmt and keeps the control. A job could then
program, for example, a 10-bit picture into buffers sized for 8 bits.

When a job is built, derive the picture format from the control value the
job uses and refuse the job unless it is the one the buffers were sized for
(ANY sizes them as 8-bit 4:2:0) and the negotiated CAPTURE format fits it.
The format each codec derives is unchanged; get_image_fmt now shares it.

Add KUnit cases for the check.

Signed-off-by: Ryan Murray <ryan@aurorasilicon.org>
V4L2_CID_STATELESS_AV1_TILE_GROUP_ENTRY is a dynamic array. Setting a
larger array through VIDIOC_S_EXT_CTRLS reallocates the control's
storage and frees the old one under the control lock, but the run kept
ctrl->p_cur.p and ctrl->elems and read the entries without that lock,
in avd_av1_check_tiles() and again later in set_tiles(). The entries
used to build the tiles could therefore be freed memory, or differ from
the ones that were checked.

Copy the entries and their count under v4l2_ctrl_lock(), as the HEVC
code does for its dynamic arrays, check the copy and build the tiles
from it, and free it on every exit of avd_av1_run(). Also take the tile
grid (tile_rows, tile_cols) from the frame control once and use that
same grid for the check, the job size and set_tiles(), so the number of
entries read can not exceed the number that was checked if the frame
control is set at the same time.

Add a KUnit test that the copy holds the entries and count after the
control's storage has been replaced and freed.

Signed-off-by: Ryan Murray <ryan@aurorasilicon.org>
avd_h264_start() sized each bank's slice table, and through it the job
table of the first picture, at one slice per row of the SPS, without
the avd_h264_max_slices() limit the run path applies when the table
grows. Take the smaller of the two, as avd_h264_realloc_slices() does.

These tables and the codec context are allocated in the context of the
STREAMON caller; charge them to it with GFP_KERNEL_ACCOUNT.

Add a KUnit test that the initial count is one per row and never
exceeds the slice table limit, whatever the SPS geometry.

Signed-off-by: Ryan Murray <ryan@aurorasilicon.org>
Every open() allocated the context's 12 MB coherent instruction FIFO,
although it is only handed to the hardware for frames, which run while
the OUTPUT queue streams. Allocate it when OUTPUT starts streaming,
before the codec's start(), and free it when OUTPUT stops, after the
context's frames have been drained and the codec's own buffers freed.
release() still frees it for a context closed while streaming.

Signed-off-by: Ryan Murray <ryan@aurorasilicon.org>
H.264 and VP9 size their per-stream scratch rows at STREAMON(OUTPUT) from
the picture format of that moment. s_ctrl only refuses a format change
while CAPTURE buffers are allocated, so a format control set after
STREAMON(OUTPUT) and before the CAPTURE buffers, or after they were freed,
changed the picture format without resizing the scratch.

Record the format the scratch was sized for, and have the run-time picture
format check refuse a job whose bit depth differs from it. H.264 STREAMON
now also checks and sizes from the SPS's current value rather than from
the last value tried.

Add a KUnit case for the scratch check.

Signed-off-by: Ryan Murray <ryan@aurorasilicon.org>
A run reads the codec's parameters from the current value of the
controls. The request's controls are applied before that, but a control
can also be set directly while the run is in progress, and its value is
then rewritten under the control lock, which the run does not hold. A
run that checks a value and later reads it again from the control can
see two different values.

Add avd_ctrl_copy(), which copies the current value of a fixed-size
control under the control lock and refuses a destination of another
size, so that a run can check and use one private copy. The dynamic
arrays are already copied this way.

v4l2_ctrl_find() takes the same lock, so the lookup is done first and
avd_ctrl_copy_value() copies a control that was already found.

The KUnit cases check that a copy keeps its value when the control is
set again, that the size is checked, and that the copy waits for the
holder of the control lock.

Signed-off-by: Ryan Murray <ryan@aurorasilicon.org>
The run validates the SPS, PPS and slice parameters and then builds the
instructions from the same controls, reading them from the controls'
current values each time. A control that is set directly meanwhile
changes those values, so the builders could use parameters other than
the ones that were checked.

Copy the decode parameters, SPS, PPS, slice parameters, scaling matrix
and prediction weights with avd_ctrl_copy() once the request has been
applied, into storage that belongs to the context, and point the run at
the copies.

Signed-off-by: Ryan Murray <ryan@aurorasilicon.org>
The run checks the sequence and the frame and then builds the
instructions from the same controls, reading them from the controls'
current values each time. A control that is set directly meanwhile
changes those values, so the builders could use parameters other than
the ones that were checked.

Copy the sequence, frame and film grain with avd_ctrl_copy() once the
request has been applied, into storage that belongs to the context, and
point the run at the copies. The tile group entries are already a
private copy.

Signed-off-by: Ryan Murray <ryan@aurorasilicon.org>
The frame's upscaled_width is written to the frame header and divides
the superres scale factors, but nothing checked it. Only the frame width
and height were compared with the CAPTURE format.

Superres only widens a frame, from frame_width to upscaled_width, and
without it the two are equal. Require, on the run's copy of the frame,
that upscaled_width is at least the frame width and at most the CAPTURE
width, and that it equals the frame width when superres is off. Move the
existing frame size check into the same helper and compare the
minus-one fields directly, so that the largest value cannot wrap to a
size of zero.

With superres the denominator is also written to the header less one;
the stream codes it as 9 to 16 and the control core only bounds it from
above, so require at least 9.

Add KUnit cases for the helper.

Signed-off-by: Ryan Murray <ryan@aurorasilicon.org>
…is set

The VP9 and AV1 frame sizes are only compared with the formats when a
frame runs. Compare them when the frame control is set as well, with the
checks the run uses, so that a frame that cannot be decoded is refused
at the control like an H.264 SPS is.

A control may be set before the formats, so only check against a format
that can no longer change: the OUTPUT format once the OUTPUT queue
streams for VP9, whose scratch is sized from it, and the CAPTURE format
once CAPTURE buffers are allocated for AV1, whose frame must fit them.
The AV1 frame control gets the driver's control ops for this.

Add KUnit cases for both.

Signed-off-by: Ryan Murray <ryan@aurorasilicon.org>
The legacy transport programs the address of the context's instruction
FIFO into the decoder for every submission. The FIFO is allocated when
the OUTPUT queue starts streaming and freed when it stops, so the
address is only valid in between. No path submits outside of that, but
nothing in the submission says so.

Refuse the submission with -EINVAL when the FIFO is not allocated,
together with the other checks of the frame and before any register is
written. Add a KUnit case.

Signed-off-by: Ryan Murray <ryan@aurorasilicon.org>
…lice

avd_hevc_check_slices() gives the last tile of a slice the bytes that
the entry point offsets leave. Cover offsets that add up to more than
the slice's data while each of them, and their sum, still lies inside
the payload: in a single slice, and in the first and the second of two
slices.

Signed-off-by: Ryan Murray <ryan@aurorasilicon.org>

@DjDeveloperr DjDeveloperr left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Formal §1–§6 pre-PR review at 752c8813f260.

The production kernel changes across all 18 commits are well-designed and carefully bounded:

  • HEVC avd_hevc_check_slices() bounds payload <= INT_MAX, checks slice CTB addresses, collocated reference indices, and segment/entry-point byte ranges in s64 without overflow, and stream_slice_mv() guards decode->dpb[col] while preserving missing-reference (0xff) decoding.
  • VP9 avd_vp9_next_tile() eliminates wrap/underflow and NULL-mapping hazards on every tile including the last, and enforces coded-format bounds.
  • AV1 bounds tile_row/tile_col, upscaled_width, and superres_denom >= 9, and snapshots tile_group and fixed controls under the control lock.
  • TRY_FMT(CAPTURE) no longer mutates ctx->comp, H.264 SPS size and start_slices are bounded with GFP_KERNEL_ACCOUNT, avd_check_run_image_fmt() checks negotiated + scratch bit depth at run time, and ctx->inst moves to STREAMON/STREAMOFF with !ctx->inst.cpu checked in avd_open_submit().
  • §1–§4 and §6 pass (no model gating, default cmdline, human author/committer and Signed-off-by: only across all 18 commits, zero AI trailers in commits).

Blockers

  1. Stacked on unmerged #2945 (base: avd/tile-bounds) with 0 CI checks run: host-tests.yml triggers only on integration/aurora and aurora-wip, so CI has not run on this PR, and #2945 is currently failing host-tests. Once #2945 is fixed and lands (or this PR is retargeted to integration/aurora), host-tests must pass.
  2. Host test harness breakages (avd-codec-tail-tests and avd-av1-tail-tests) — once host-tests runs on this stack, it will fail on:
    • drivers/media/platform/apple/avd/tests/program-test.py: in addition to the #2945 struct avd_job / avd_hevc_check_sps_geometry issues, avd_h264_run_preamble() changed from void to int (program-test.py:421 stubs void), avd_h264_run() now calls avd_check_run_image_fmt() and avd_h264_sps_image_fmt(), and avd_h264_validate_sps() now carries VISIBLE_IF_KUNIT.
    • tools/asahi/avd-av1-tail-tests.py:
      • host_source.function(src, 'avd_av1_check_tiles') regex will miss the preceding VISIBLE_IF_KUNIT int line when split across two lines.
      • avd_av1_run_preamble() now dereferences ((struct avd_av1_ctx *)ctx->priv)->stream (av1.stream is NULL in avd-av1-tail-tests.py:142) and calls avd_ctrl_copy(), avd_check_run_image_fmt(), avd_av1_seq_image_fmt(), avd_av1_check_frame_size(), and avd_av1_copy_tile_group().
      • Test fixtures at lines 115, 144, and 168 leave frame.upscaled_width == 0, which avd_av1_check_frame_size() now rejects with -EINVAL.
      • Mutation frame-width-unchecked (avd-av1-tail-tests.py:232) searches avd_av1_run_preamble for the old inline width check that moved into avd_av1_check_frame_size().
    • drivers/media/platform/apple/avd/tests/av1-test.py (run by avd-codec-tail-tests.py:194): also extracts avd-av1.c and will need updates for avd_ctrl_copy, avd_check_run_image_fmt, v4l2_ctrl_lock/kmemdup_array, and frame.upscaled_width.

Please update the AVD host tests alongside #2945 and verify host-tests green after retargeting to integration/aurora.

Assisted-by: LLM (Gemini 4 Neon)

…heck

The host program test models struct avd_job without the new max and
overflow fields, so push() treats every job as full. Give the model
the fields and set max wherever a test builds a segment table.

avd_hevc_validate_sps() now calls avd_hevc_check_sps_geometry(), which
the test did not extract, and the depth fixture used 8x8 CTBs, which
the check refuses. Extract the helper and use 64x64 CTBs. Let the
extractor find functions whose return type is on the previous line.

Signed-off-by: Ryan Murray <ryan@aurorasilicon.org>
avd_hevc_check_tiles() reads column_width_minus1[] and
row_height_minus1[] up to the tile counts and relied on the V4L2
control code to keep the counts below the array sizes. Check that in
the helper too, so it holds for any caller.

Signed-off-by: Ryan Murray <ryan@aurorasilicon.org>
The H.264 and AV1 runs now take copies of their controls, check the
picture format against the buffers and, for AV1, check the frame size
and copy the tile group under the control lock. Update the host
fixtures to match:

- avd_h264_run_preamble() returns an int; avd_h264_sps_image_fmt() is
  extracted, and the fixtures use the driver's image format enum.
- avd_check_run_image_fmt() is stubbed; avd-fmt-test.c covers it.
- The AV1 fixtures provide the stream's control copies, the control
  lock, kmemdup_array() and the OUTPUT buffer the preamble reads, and
  set upscaled_width, which must now equal the frame width without
  superres.
- The AV1 tail test extracts the new helpers, and its frame size
  mutation drops the frame size check in avd_av1_check_frame_size()
  as a whole: the upscaled width bound alone also bounds the width.

Signed-off-by: Ryan Murray <ryan@aurorasilicon.org>
@RyanTheTide
RyanTheTide changed the base branch from avd/tile-bounds to integration/aurora November 23, 2026 06:59
@RyanTheTide

Copy link
Copy Markdown
Author

Thanks for the review. Pushed (305193d), no history rewrite:

  • merged the fixed avd/tile-bounds (media: apple: avd: check HEVC tile layouts and VP9 tile counts before building jobs #2945 at 5e26308) in, so this branch carries the same commits;
  • 305193da tests: avd_h264_run_preamble() stub returns int; avd_h264_sps_image_fmt() is extracted and the fixtures use the driver's enum avd_image_fmt (the old prelude macros had different values); avd_check_run_image_fmt() is stubbed in the program and AV1 fixtures (avd-fmt-test.c covers it in KUnit). AV1 fixtures: control lock, kmemdup_array(), elem_size, avd_ctrl_copy(), the stream's control copies and the OUTPUT buffer the preamble reads; upscaled_width set in the fixtures. The AV1 tail extractor finds VISIBLE_IF_KUNIT int / struct ... * / enum returns on the previous line and extracts the new helpers. The frame-width-unchecked mutation now drops the frame-size test in avd_av1_check_frame_size() as a whole: the upscaled-width bound alone also bounds the width, so removing only the width clause is an equivalent mutant (it is killed by the height guard now).
  • Retargeted to integration/aurora so host-tests runs on the stack (the diff shows media: apple: avd: check HEVC tile layouts and VP9 tile counts before building jobs #2945's commits until it merges).

Local results at 305193d: run-host-tests.py --only avd 12/12 (all AV1 tail mutations fail as they should); KUnit+KASAN (avd-pm.kunitconfig, arm64) 168/168.

@DjDeveloperr DjDeveloperr left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Formal §1–§6 pre-PR checklist re-review at 305193da4ba7e79eecfb444394faf5cbc79344c6.

Follow-up Verification (since 752c8813f260)

  • Prior Blocker 1 (non-default stacked base avd/tile-bounds / 0 CI checks) — Resolved: PR is now retargeted to integration/aurora, cleanly merges the fixed #2945 (5e263083adeb) via 1c7a1f3b3b1c (verified zero unintended diff outside the 6 #2945 follow-up files), and live CI host-tests (run 45127925323) is green: 463/463 passed.
  • Prior Blocker 2 (AVD host test harnesses) — Resolved: Commit 305193da4ba7 cleanly updates:
    • drivers/media/platform/apple/avd/tests/program-test.py: matches enum avd_image_fmt from avd.h, updates avd_h264_run_preamble() to return int, extracts avd_h264_sps_image_fmt(), and stubs avd_check_run_image_fmt() (covered by KUnit avd-fmt-test.c).
    • drivers/media/platform/apple/avd/tests/av1-test.py: adds v4l2_ctrl_lock/unlock, kmemdup_array(), elem_size, avd_ctrl_copy(), and avd_check_run_image_fmt() stubs.
    • tools/asahi/avd-av1-tail-tests.py: handles multiline VISIBLE_IF_KUNIT / enum / pointer return types, extracts avd_av1_copy_tile_group, avd_av1_seq_image_fmt, and avd_av1_check_frame_size, initializes fixture_dev/fixture_stream/fixture_src/upscaled_width, and updates frame-width-unchecked against avd_av1_check_frame_size(). All 12 AVD host tests (avd-av1-tail-tests + cases + all 6 mutations, avd-codec-tail-tests + --mutations) passed in CI.

Checklist Summary (§1–§6)

  • §1 No model gating: Pass — codec-generic AVD validation and bounds hardening, zero chip/SoC/board/firmware gates.
  • §2 Production-ready: Pass — default command line, no new parameters, delays, or lab-only paths.
  • §3 Safety: Pass — HEVC slice/DPB/entry-point bounds (preserving 0xff missing-ref decoding), VP9 tile bitstream bounds and frame-size checks, AV1 tile-grid/upscaled_width checks and locked control/tile-group copies, TRY_FMT(CAPTURE) local copy, H.264 SPS size and capped GFP_KERNEL_ACCOUNT slice table, run-time format/bit-depth checks, and STREAMON/STREAMOFF context FIFO lifecycle with !ctx->inst.cpu guard.
  • §4 Clean-room & attribution: Pass — all 26 patch commits carry human author/committer (Ryan Murray <ryan@aurorasilicon.org>) and human Signed-off-by: only, merge commit 1c7a1f3b3b1c carries human author/committer only, zero AI trailers in any commit; PR body includes Assisted-by:; clean-room.
  • §5 Evidence & CI: Pass — host-tests CI green (463/463); KUnit+KASAN (avd-pm.kunitconfig, arm64 QEMU) 168/168 pass (all new tests confirmed failing without fixes, including AV1 UAF KASAN hit); M2 (T8112, default boot 7.3.0-aurora-fleet82, default cmdline) A/B confirms bit-exact output across 9 decode clips and 1080p/4K avd-bench, clean refusal of malformed parameters (0 oops/KASAN/DART faults), and 64 non-streaming opens dropping MemFree by ~1.9 MB confirming STREAMON FIFO deferral.
  • §6 Naming: Pass.

Non-blocking Notes

  • Merge order: #2946 carries the exact 7 commit SHAs of #2945 (5e263083adeb, ahead by 20 commits, behind by 0), so merging #2945 first in MERGETRAIN-LINUX4 lets #2945 close cleanly before #2946 merges on top.
  • Minor hygiene: the PR body still mentions "Before merging #2945, retarget this PR to integration/aurora" (already done), and M1-family / M4-family follow-up rows plus an explicit SELinux/systemd regression tuple are welcome when convenient.

Verdict

APPROVE — both prior blockers cleanly resolved, base retargeted to integration/aurora, CI green, ready for MERGETRAIN-LINUX4 (after or alongside #2945).

Assisted-by: LLM (Gemini 4 Neon)

@RyanTheTide

Copy link
Copy Markdown
Author

Merge-train review at 305193d (non-author pass): BLOCKER(s)

There are no code blockers. The one blocker is evidence: this PR changes the AV1 run path substantially (copies of the controls and the tile group, the frame-size and upscaled_width checks, the tile row/col bound, and a new AV1_FRAME try_ctrl), and no AV1 frame has been decoded on hardware at or equivalent to head. The only row is on M2 (T8112), whose AVD has no AV1 (in the row log, av1-tiles-1080 gives the md5 of empty input on both arms). Before merge I'd like one AV1 real-stream row on an AV1-capable Mac (T8122/T8132/T6040/T8140 class). In the same session, please add an H.264 multi-slice clip that actually produces output (h264-slices was also empty on both arms, and the slice table cap is in this PR), plus one 10-bit clip each for HEVC Main10 and VP9 profile 2, since the new run-time format and scratch-depth checks act on 10-bit specifically. A recipe is below.

Code: every check I tried to break holds, the error paths complete the request and retire the frame cleanly, the limits come from the codec specs, there are no gates or new parameters, and the trailers are human-only (merge commit included). The PR merges cleanly onto integration/aurora 5441428. Host tests 12/12 and KUnit+KASAN 168/168 pass at head, and all 7 mutations I made to the checks were caught.

False positives checked (valid streams that could now be refused)
  • HEVC slices: avd_hevc_check_slices() follows the same segment layout as stream_slices(): the same to, the same last-segment size and offset, and the same entry point accounting. Entry point offsets include emulation prevention bytes (7.4.7.1), as the builder assumes. The collocated bound uses l0 for P slices or COLLOCATED_FROM_L0, otherwise l1, the same choice stream_slice_mv() makes. It applies only with TMVP. The < 16 bound without TMVP is safe because GStreamer, FFmpeg and Chromium leave collocated_ref_idx at 0 when it is absent. The 0xff missing-reference case still decodes.
  • HEVC tiles: segments per tile without WPP give pos <= number of tiles, so the new row + 1 >= ARRAY_SIZE(row_bd) guard cannot fire for tiles-only streams (slices that span tiles must contain whole tiles).
  • H.264 SPS size vs coded format: GStreamer, FFmpeg and Chromium set OUTPUT to the MB-aligned coded size (including the 2x for frame_mbs_only=0), and S_FMT rounds up (step 64/16), so 1366x768, 1080p and 1080i pass. Only a client that sets OUTPUT to the cropped size of an interlaced stream whose height is not a multiple of 32 could be refused (for example 486 lines rounds to 496 but needs 512). That is rare, and before this PR it would have overrun the scratch anyway.
  • VP9: frames larger than the coded format are refused only while OUTPUT streams. Dynamic resolution changes go through STREAMOFF/S_FMT in GStreamer and FFmpeg.
  • AV1: upscaled_width == frame_width without superres and superres_denom >= 9 match what GStreamer, FFmpeg and Chromium send (SuperresDenom = coded_denom + 9). The driver already used upscaled_width unconditionally (ref scaling and the header), so a client that sent 0 was already broken.
  • avd_check_run_image_fmt(): ANY and 420_8BIT compare equal, and fill_comp() treats ANY as 8-bit 4:2:0, so 8-bit streams whose SPS never reached s_ctrl still pass. A 10-bit stream is refused if its format control never reached s_ctrl before CAPTURE was sized. Before this PR that case wrote 10-bit output into 8-bit-sized buffers, so refusing it is correct. It is still a reason to have a 10-bit row.
Overflow, races and error handling
  • Job table: HEVC builds sum(num_entry_point_offsets+1) segments and gets num_slices + num_entry_points + 1 entries. VP9 gets tiles + 1, AV1 rows*cols + 1 (at most 4096 after the 64x64 bound), and H.264 regrows and updates max. push() plus avd_open_build_program() refuse anything that goes past the table.
  • VP9 tile walk: avd_vp9_next_tile() has no u32 wrap (it compares payload - off after off <= payload), checks for a NULL mapping, and applies the bound to the last tile too.
  • Context FIFO: freed after avd_queue_drain(). avd_buf_free() memsets, so the release path and a repeated STREAMON are idempotent, and avd_open_submit() refuses when there is no FIFO.
  • Errors: every refused job goes through avd_run_postamble() (the request completes) and then the fail: path in avd_queue (the frame is DONE with an error and the m2m job is detached). The HEVC/VP9/AV1 copies are freed on all exits.

Non-blocking notes:

  1. The H.264 and AV1 copies are taken per control (six and three separate lock acquisitions), so a client racing plain S_EXT_CTRLS can mix two settings. Every check reruns on the copies, so memory safety holds and only that misbehaving client's output suffers. One lock span would make the snapshot atomic.
  2. A non-last VP9 tile of size 0 is now refused. That follows VP9 9.2.1 (sz >= 1), and libvpx never writes one, but libvpx's decoder does tolerate it.
  3. Tiles plus WPP with more than 22 segment rows is refused (documented in the PR). Version 1 Main forbids that combination; I believe later H.265 editions relax it for Main/Main 10, so it is worth a follow-up. Before this PR the case read past the table, so nothing is lost.
  4. The row log shows one HEVC frame with synthetic controls that passed every check and still timed out (recovery took 6 ms). That is the hardware, not this PR, but bounds checks alone do not make the engine hang-proof.
Tests and mutations

Scratch worktree at 305193d:

  • tools/asahi/run-host-tests.py --only avd --jobs 8: 12/12 (AV1 tail including 6 mutations, codec tail including --mutations).
  • kunit.py run --arch=arm64 --kunitconfig=drivers/media/platform/apple/avd/avd-pm.kunitconfig --kconfig_add CONFIG_KASAN=y: 168/168. The KUnit files call the driver's own functions (VISIBLE_IF_KUNIT exports). The host tests extract the real source.
  • Mutations, each caught by KUnit:
    • HEVC TMVP bound > last changed to > last + 1: caught by "P slice, collocated index past the active list".
    • Scratch-depth clause dropped from avd_check_run_image_fmt(): caught by avd_fmt_scratch_depth_test.
    • AV1 tile_col bound dropped: caught by 4 avd_av1_tiles_rowcol cases.
    • H.264 SPS height bound loosened by 16: caught by "720p, one row over".
    • Also caught (media: apple: avd: check HEVC tile layouts and VP9 tile counts before building jobs #2945 code): the HEVC tile sum off-by-one, push() >= changed to > (KASAN), and the VP9 size word < 4 changed to < 3.
Owed rows and recipe

Owed before merge (head kernel, or the head avd module swapped over a matching fleet kernel as in the M2 row, default cmdline, stock module as the A arm):

  • AV1: one Mac with AV1 in its AVD (T8122, T8132, T6040 or T8140 class). Include at least one tiled stream and one 10-bit stream; a superres stream is a bonus.
  • H.264 multi-slice with real output (replace h264-slices, which gave nothing on either arm), plus HEVC Main10 and VP9 profile 2, on the same Mac.

Wanted: the same rows on an M1-family Mac for the second generation of H.264/HEVC/VP9.

Recipe (per clip, hardware vs software, frame hashes):

# 8-bit: FMT=I420; 10-bit: FMT=I420_10LE
gst-launch-1.0 -q filesrc location=$CLIP ! parsebin ! v4l2slav1dec ! videoconvert ! video/x-raw,format=$FMT ! checksumsink hash=md5 > hw.txt
gst-launch-1.0 -q filesrc location=$CLIP ! parsebin ! av1dec       ! videoconvert ! video/x-raw,format=$FMT ! checksumsink hash=md5 > sw.txt
diff hw.txt sw.txt && echo BITEXACT
# likewise v4l2slh264dec/avdec_h264, v4l2slh265dec/avdec_h265, v4l2slvp9dec/vp9dec

Alternatively, run fluster on the same Mac, stock vs head, and compare the pass sets (head must pass everything stock passes):

fluster.py run -d GStreamer-AV1-V4L2SL-Gst1.0 -ts AV1-TEST-VECTORS
fluster.py run -d GStreamer-H.264-V4L2SL-Gst1.0 -ts JVT-AVC_V1
fluster.py run -d GStreamer-H.265-V4L2SL-Gst1.0 -ts JCT-VC-HEVC_V1
fluster.py run -d GStreamer-VP9-V4L2SL-Gst1.0 -ts VP9-TEST-VECTORS

JVT-AVC_V1 has the multi-slice streams, JCT-VC-HEVC_V1 the TILES_/WPP_/ENTP_* and *_MAIN10 streams, and AV1-TEST-VECTORS the 10-bit streams.

Also record the dmesg health line (0 oops/KASAN/DART faults/avd timeouts) and confirm that the stock and head pass sets match. In the current kit, 8 of the 9 M2 md5s differ from the software reference even on stock, so a per-frame diff vs software is the more useful signal than A/B identity.

Assisted-by: LLM (Claude:Opus 5.5)

@RyanTheTide RyanTheTide left a comment

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Independent source review at 305193da4ba7. The M2 bit-exact decode row covers the codecs its AVD can exercise. The AV1 tile copy and lifetime changes still need an AV1-capable default-kernel row, and the shared run-time format check needs the changed-format case, not only stock 1080p/4K decode. Include those on the final stack before land.

@RyanTheTide

RyanTheTide commented Nov 23, 2026 •

Copy link
Copy Markdown
Author

The standalone VP9 host fixture needs a follow-up for the scratch-format fields at 305193da4ba7. I tested this head with the control-copy fixture repair from #2972, added the scratch fields and wired the fixture to the production format check. The standalone VP9 suite then passed under ASan and UBSan. The program fixture on this head already supplies the image-format enum.

@RyanTheTide

Copy link
Copy Markdown
Author

I prepared a valid-input control for the remaining decode row. Host results on GStreamer 1.28.4 and FFmpeg 8.1.2:

  • H.264 High, 1280×720: 48/48 per-frame NV12 hashes on each of five streams. The four-slice baseline has 192 slice headers. The one-slice control has 48. The other four-slice streams independently disable deblocking, 8×8 transforms or B-frames.
  • AV1 Main 10, 1280×720: 24/24 per-frame hashes match in both I420_10LE and P010. The bitstream signals two tile rows and two tile columns.
  • Use videoconvert dither=none for the 10-bit software reference conversion if comparing P010. Default dithering in the P010 conversion changed 24/24 hashes in the initial software-to-software comparison.

These are software reference checks. The hardware gate still needs the tiled 10-bit AV1 stream and H.264 multi-slice, HEVC Main10 and VP9 Profile 2 on an AV1-capable device at this PR head, alongside the stock A arm. The M2 decoder cannot provide the AV1 row.

Fixture generation and software reference command
ffmpeg -f lavfi -i testsrc2=size=1280x720:rate=30 -an -frames:v 48 \
  -pix_fmt yuv420p -threads 4 -c:v libx264 -profile:v high \
  -x264-params slices=4 multislice.mp4
ffmpeg -f lavfi -i testsrc2=size=1280x720:rate=30 -an -frames:v 24 \
  -vf format=yuv420p10le -threads 4 -c:v libaom-av1 -cpu-used 8 \
  -tiles 2x2 -crf 38 -b:v 0 tiled10.mkv
gst-launch-1.0 -q filesrc location=tiled10.mkv ! matroskademux ! av1parse \
  ! av1dec ! videoconvert dither=none ! video/x-raw,format=P010_10LE ! fdsink fd=1

@RyanTheTide
RyanTheTide merged commit def4cfc into integration/aurora Nov 23, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants