mu300-voice ends its players on TERM/INT/HUP; audio-sipc drops DSP replies nobody waited for (FINDINGS 188)

A TERM to a running mu300-voice call/demo/echo left its aplay/arecord holding the voice PCM, and the next run
failed with "Resource busy". Every player is now a waited-for background child that TERM, INT, HUP and exit end;
a busy PCM held by a leftover of an earlier run is ended and retried, anything else is reported. An open that
fails with EIO is tried once more (a fresh open, never a restart after an xrun).

The EIO itself: each play into FE_ST_VOICE_PCM_P leaves two KCTL_SET replies the driver never waits for, and
aud_recv_cmd() failed a STARTUP on the first reply for another command, so five queued failed the next
FE_ST_DUMP open. A reply for another command is now dropped and the wait goes on within the same timeout; the
drain reads until the cache is empty. The same change for 5.4 as kernel/patches/audio-sipc-stale-reply.patch.

Both reproduced on F50-B (7.2.11) without a call; the script fix measured there, the driver fix unit-tested
against a fake message cache and built for 7.2.11 and 5.4.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VVN2zDgf76kMDVSuWhHPUE
This commit is contained in:
Abdurrahman Kaan DikeçandClaude Opus 5.5 committed 2026-10-18 12:57:15 +03:00
1 parent 2c06845c11
commit b1f59b81ec
6 files changed
+660 -40

No files matched your search

+58 -1
View File
@@ -179,7 +179,7 @@ what replaced it. The table below gives each section's state.
| 175 | The U30 Air's firmware SAE offload disabled in every layer: the driver drops the PMK record and refuses the vendor command, no hostapd import, the wifi-scripts refuse SAE, a hotspot left on SAE becomes WPA2-PSK with the same password (or off, never open) with a notice | current (unit tests; the driver built for 5.4 (objects), 6.18 and 7.2; on the U30 Air (OpenWrt, 6.18.57): refusal, migration, notice, the panel's save; no F50 yet) |
| 180 | Wi-Fi access point: `get_station` answered any address with the interface's own counters and the station side's signal; now only this AP's stations, with nothing filled in (the firmware has no per-client figures), `-ENOENT` otherwise; `get_channel` link 0 only (kanoqwq f59a296) | current (mainline module and 5.4 patch built; unit tests; U30 Air 6.18.57 with a client, F50-B 7.2.11, 2026-10-17) |
| 181 | The U30 Air's fuel gauge against the stock module: the user area's writes are `regmap_update_bits()` with a wait after the release (stock `save_last_cap` at 0x4ba4), no migration guess for a valid saved value, the charger's Full is 100 % with the battery current within `fullbatt-current` (kanoqwq f59a296 reviewed: his 4.2 V condition would refuse a real Full) | current (built for 6.18.57 and 7.2.11; unit tests; U30 Air 6.18.57, 2026-10-17: Full at 4.147 V gave 100 %, kept across a reboot) |
| 188 | Call audio on the mainline kernels: the 5.4 stack (19 modules + the vendor AGDSP DMA) built for 6.18.57 and 7.2.11, the DSP's memory reserved (patch 0022), nothing autoloaded; the xrun restart that panicked 5.4 fixed (descriptors re-armed in `prepare`), the DSP's DDR mapped Normal-NC (7.x memcpy alignment fault), no 6 s spin under a lock waiting for the AGDSP domain, the domain held across the DSP start (warm reboots), the echo played at the tap's 16 kHz mono | current (F50-B 6.18.57 and 7.2.11, F50-C 7.2.11 OpenWrt, offline; a call on F50-C 7.2.11: ringback 425 Hz, melody heard, downlink recorded (his voice, F0 140 Hz); the echo through the fixed path, answered call 22:41: the owner heard his voice and the melody) |
| 188 | Call audio on the mainline kernels: the 5.4 stack (19 modules + the vendor AGDSP DMA) built for 6.18.57 and 7.2.11, the DSP's memory reserved (patch 0022), nothing autoloaded; the xrun restart that panicked 5.4 fixed (descriptors re-armed in `prepare`), the DSP's DDR mapped Normal-NC (7.x memcpy alignment fault), no 6 s spin under a lock waiting for the AGDSP domain, the domain held across the DSP start (warm reboots), the echo played at the tap's 16 kHz mono | current (F50-B 6.18.57 and 7.2.11, F50-C 7.2.11 OpenWrt, offline; a call on F50-C 7.2.11: ringback 425 Hz, melody heard, downlink recorded (his voice, F0 140 Hz); the echo through the fixed path, answered call 22:41: the owner heard his voice and the melody; after a killed call, no player left behind and DSP replies nobody waited for no longer fail the next open: reproduced on F50-B without a call, script fix measured there, driver fix unit-tested) |
## Hardware and firmware facts
@@ -2494,6 +2494,63 @@ values from userspace without checking them.
Not measured on mainline: a call to a Bluetooth headset (the `bt` route of 24c), and a program that bridges the
voice taps for a whole call (it reads the dump and writes the uplink at 16 kHz itself, so it needs no change).
**Two faults after a killed test call (F50-C, 7.2.11, 2026-10-18), and their fixes.** The owner stopped a running
`mu300-voice call` with a TERM. The next `call` failed with `aplay: audio open error: Resource busy`, for the melody
and for the echo. After that, the first FE_ST_DUMP open failed with EIO, and the open after it worked. Both were
reproduced on F50-B (Ubuntu 24.04, 7.2.11, the release's audio stack, the 41S image) without a call: the hostless
scene, `demo`, `echo`, and plain opens of the PCMs.
* *The player outlived the script.* `mu300-voice` ran aplay and arecord in the foreground, and the melody's aplay
in a `$(...)`. A TERM ended the shell and nothing else. A shell also runs its trap only after the foreground command
returns, so a trap alone would not have helped. On F50-B: `echo 30` was killed during its arecord, and the arecord
kept FE_ST_DUMP (`pcmC1D16c`) open to the end of its 30 s. A second `echo` then failed with `audio open error:
Device or resource busy`. `echo 2` was killed during the echo's `aplay -D mu300_uplink`, and that aplay was still
holding `pcmC1D53p` a minute later. That is the owner's orphan; without a call the tap does not move, so it waits.
The same happened with INT.
Now every aplay/arecord is a child. The script starts it in the background and waits for it. TERM, INT, HUP and exit
end each child (TERM, then KILL after 3 s) and wait until it has gone, so its PCM is closed. A scene that is still
starting is stopped and its controls are put back. A scene that has started belongs to the call and stays (`audio
stop`, `hangup`), as before. On F50-B, TERM, INT (sent as a terminal sends it) and HUP each ended the script in
0.1-0.2 s with nothing left on either PCM.
When an open reports busy, the script says who holds the node (from `/proc/*/fd`; OpenWrt's busybox has no
`fuser`). If the holder is an aplay or arecord playing or recording one of the script's own files in
`/run/mu300-voice`, it is a leftover of an earlier run: the script ends it and tries once more. Anything else is
only reported. With the old script's one-minute-old orphan on `pcmC1D53p`, the new `echo` printed
`/dev/snd/pcmC1D53p is held by pid … (aplay), left over from an earlier mu300-voice: ending it` and went on.
Ending a player is a close of its PCM. Nothing here prepares and starts a stream again after it stopped, which
panics 5.4 (24e).
* *DSP replies nobody waited for.* On the VBC control channel, the DSP's replies are read in order.
FE_ST_VOICE_PCM_P's trigger and its shutdown send a KCTL_SET (cmd 9, `SND_KCTL_TYPE_VOICE_MIX_UL`) with
`aud_send_cmd_no_wait_param()`. The DSP answers each one anyway, so every play into the uplink tap leaves two replies
in the channel's cache. A sender whose wait is interrupted leaves its reply too. The next KCTL_SET that does wait
drains them, because they carry its own command number. A STARTUP (cmd 4) does not:
`aud_recv_cmd()` failed on the first reply for another command. The drain before the send stopped there, and each
of the wait's 4 tries read one more. With five queued, the open failed:
`aud_recv_cmd, Haven't got right cmd(0x4), got cmd(0x9)` five times, then `aud_send_cmd: failed to get
command(4), ret=-5`, `dsp_startup: … vbc_dsp_func_startup return error`, and `ASoC error (-5) … BE_DAI_ID_DUMP`.
This is the same log as F50-C's. It took no kill. On F50-B, after `audio start dsp`, one play into
`hw:1,53` before a FE_ST_DUMP open gave `cmd =4 … repeat_count=4`, a pass by one try. Three plays gave the EIO
every time. `demo` reaches the state by itself: without a call each of the melody's three framings fails, which
makes six plays. The next open worked because the failed one had read five replies. The answer to the failed
STARTUP is then left in the cache too, and a later KCTL_SET read `got cmd(0x4)`.
* Fix in the driver (`upstream/modules/sprd_audio/.../audio-sipc.c`): a reply for another command is dropped
(`dropped a stale reply` in dmesg), and the wait goes on for the right one within the same timeout. A deadline
replaces the fresh 3 s of each try. With timeout 0 (the drain), it reads until the cache is empty, at most 256
replies. The 5.4 driver has the same function line for line. It gets the same change as
`kernel/patches/audio-sipc-stale-reply.patch`, the eighth patch of `build-audio.sh`, and in
[mu300-audio](https://github.com/dikeckaan/mu300-audio)'s prebuilt `audio_sipc.ko`.
* Fix in the script: an open that fails with `audio open error: Input/output error` is tried once more, after
0.5 s, as a new open. That covers a kernel without the fix. On F50-B with the release driver: `demo 2` printed
`/dev/snd/pcmC1D16c: the DSP refused the open (EIO), trying once more`, and the second open went through
(`repeat_count=1`) into the echo loop. The old script stopped at `capture failed`.
* Measured for the driver change: `tests/test_voice_cleanup.py` compiles `aud_recv_cmd()` against a fake message
cache. It covers the drain past stale replies, the wait that skips them within what is left of the timeout, never
longer, a cache full of wrong replies, and the plain case. The same test fails on the old function. The module
builds for 7.2.11 (the release's config, same vermagic) and for 5.4.254. **Not run on a board yet.** Swapping
`audio_sipc` needs a boot without the audio stack (its modules are permanent once loaded), which was not done
on F50-B. The first board to boot a release with it should show, after a few plays into FE_ST_VOICE_PCM_P,
`dropped a stale reply` lines and a FE_ST_DUMP open that works the first time.
## Bluetooth
### 25. SC2355 Bluetooth on BlueZ
+3 -1
View File
@@ -71,9 +71,11 @@ fi
# Three fixes from the Rongyue E5 port of the same drivers (kanoqwq/e5-linux, same SoC family, measured there):
# period events from an hrtimer because the AGCP DMA interrupt never arrives, no DMA position read while the
# AGCP domain is asleep, and the DSP front ends offered only the formats and layouts the DSP takes.
# And one of ours: a DSP reply left behind by a killed command no longer fails the next one (FINDINGS 188).
for p in audio-pcm-period-timer:sprd_pcm_period_tick:sprd/platform/dmaengine_pcm \
audio-pcm-pointer-agcp-access:last_pointer:sprd/platform/dmaengine_pcm \
audio-fe-dai-formats:fe_dai_uses_mcdt:sprd/dai/vbc/v4/fe_dai; do
audio-fe-dai-formats:fe_dai_uses_mcdt:sprd/dai/vbc/v4/fe_dai \
audio-sipc-stale-reply:dropped:sprd_audio/audiosipc; do
name=${p%%:*}; rest=${p#*:}; mark=${rest%%:*}; dir=${rest#*:}
if ! grep -rq "$mark" $A/$dir; then
(cd $A && patch -p1 -s -f < /work/patches/$name.patch)
+112
View File
@@ -0,0 +1,112 @@
audio_sipc: drop a stale DSP reply and keep waiting, instead of failing the command it was not for
Replies on an SIPC channel are read in order, and some are never waited for: the voice PCM tap's trigger and
shutdown send a KCTL_SET (cmd 9) with aud_send_cmd_no_wait_param(), and the DSP answers each anyway; a sender whose
wait was interrupted leaves its reply too. The drain before a send stopped at the first reply for another command,
and each of the 4 tries of the wait read one more, so with 5 of them queued a STARTUP (cmd 4) failed:
"aud_recv_cmd, Haven't got right cmd(0x4), got cmd(0x9)", "aud_send_cmd: failed to get command(4), ret=-5", and the
PCM open behind it failed with EIO (FE_ST_DUMP right after a few plays into FE_ST_VOICE_PCM_P). Now a reply for
another command is dropped and the wait goes on within the same timeout, and the drain reads until the cache is
empty. Same change as mu300-linux upstream/modules/sprd_audio (the mainline port).
--- a/sprd_audio/audiosipc/audio-sipc.c
+++ b/sprd_audio/audiosipc/audio-sipc.c
@@ -23,6 +23,7 @@
#include <linux/firmware.h>
#include <linux/init.h>
#include <linux/io.h>
+#include <linux/jiffies.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/of.h>
@@ -519,41 +520,65 @@
}
EXPORT_SYMBOL(aud_ipc_ch_close);
+/*
+ * Replies on a channel are read in order, and some are never waited for: the voice PCM tap's trigger and shutdown
+ * send a KCTL_SET (cmd 9) with aud_send_cmd_no_wait_param() and the DSP answers each anyway, and a sender whose
+ * wait was interrupted leaves its reply too. They stay in the channel's cache. The drain before a send stopped at
+ * the first reply for another command, and each of the 4 tries of the wait read one more, so with 5 of them
+ * queued a STARTUP (cmd 4) failed with "Haven't got right cmd(0x4), got cmd(0x9)" and -EIO, and so did the PCM
+ * open behind it: FE_ST_DUMP right after a few plays into FE_ST_VOICE_PCM_P. A reply for another command is now
+ * dropped and the wait goes on for the right one, within the same timeout; with timeout 0 (the drain) it reads on
+ * until the cache is empty.
+ */
int aud_recv_cmd(u16 channel, u32 cmd, struct aud_smsg *result,
int32_t timeout)
{
int ret = 0;
+ int dropped = 0;
+ unsigned long deadline = jiffies + (timeout > 0 ? timeout : 0);
struct aud_smsg mrecv = { 0 };
- aud_smsg_set(&mrecv, channel, cmd, 0, 0, 0, 0);
+ for (;;) {
+ int32_t wait = timeout;
- ret = aud_smsg_recv(AUD_IPC_AGDSP, &mrecv, timeout);
- if (ret < 0) {
- if (-ENODATA == ret) {
- pr_warn("%s channel =%u cmd=%u ENODATA\n",
- __func__, channel, cmd);
- return ret;
+ if (timeout > 0) {
+ long left = (long)(deadline - jiffies);
+
+ /* never 0, which would mean "do not wait" to aud_smsg_recv */
+ wait = left > 0 ? (int32_t)left : 1;
}
- pr_err("%s, Failed to recv channel =%d cmd(0x%x),ret(%d)\n",
- __func__, channel, cmd, ret);
- return -EIO;
- }
- sp_asoc_pr_dbg("%s, chan: 0x%x, cmd: 0x%x, value0: 0x%x, value1: 0x%x,",
- __func__, mrecv.channel, mrecv.command,
- mrecv.parameter0, mrecv.parameter1);
- sp_asoc_pr_dbg(" value2: 0x%x, value3: 0x%x, timeout: %d\n",
- mrecv.parameter2, mrecv.parameter3, timeout);
+ aud_smsg_set(&mrecv, channel, cmd, 0, 0, 0, 0);
- if (cmd == mrecv.command && mrecv.channel == channel && result) {
- *result = mrecv;
- return 0;
- }
- pr_err("%s, Haven't got right cmd(0x%x), got cmd(0x%x)",
- __func__, cmd, mrecv.command);
- pr_err(" got chan(0x%x)\n",
- mrecv.channel);
+ ret = aud_smsg_recv(AUD_IPC_AGDSP, &mrecv, wait);
+ if (ret < 0) {
+ if (-ENODATA == ret) {
+ pr_warn("%s channel =%u cmd=%u ENODATA\n",
+ __func__, channel, cmd);
+ return ret;
+ }
+ pr_err("%s, Failed to recv channel =%d cmd(0x%x),ret(%d)\n",
+ __func__, channel, cmd, ret);
+ return -EIO;
+ }
+ sp_asoc_pr_dbg("%s, chan: 0x%x, cmd: 0x%x, value0: 0x%x, value1: 0x%x,",
+ __func__, mrecv.channel, mrecv.command,
+ mrecv.parameter0, mrecv.parameter1);
+ sp_asoc_pr_dbg(" value2: 0x%x, value3: 0x%x, timeout: %d\n",
+ mrecv.parameter2, mrecv.parameter3, timeout);
- return -EIO;
+ if (cmd == mrecv.command && mrecv.channel == channel) {
+ if (result)
+ *result = mrecv;
+ return 0;
+ }
+ pr_warn("%s, dropped a stale reply: cmd(0x%x) chan(0x%x) while waiting for cmd(0x%x)\n",
+ __func__, mrecv.command, mrecv.channel, cmd);
+ if (++dropped >= SMSG_CACHE_NR) {
+ pr_err("%s, Haven't got right cmd(0x%x) in %d replies\n",
+ __func__, cmd, dropped);
+ return -EIO;
+ }
+ }
}
static int aud_send_msg(u16 channel, u32 cmd, u32 value0,
+122 -13
View File
@@ -84,10 +84,13 @@ fi
# by name, not number: the device numbers are not the same on every build of the card
pcmdev() { awk -F': ' -v n="$1 " 'index($2, n) == 1 { split($1, a, "-"); print a[2] + 0; exit }' /proc/asound/pcm; }
VOICE=$(pcmdev FE_ST_VOICE); VOICE=${VOICE:-5}
PLAY=hw:$card,$(pcmdev FE_ST_VOICE_PCM_P || true)
CAP=hw:$card,$(pcmdev FE_ST_DUMP || true)
[ "$PLAY" = "hw:$card," ] && PLAY=hw:$card,53
[ "$CAP" = "hw:$card," ] && CAP=hw:$card,16
PLAY_DEV=$(pcmdev FE_ST_VOICE_PCM_P || true); PLAY_DEV=${PLAY_DEV:-53}
CAP_DEV=$(pcmdev FE_ST_DUMP || true); CAP_DEV=${CAP_DEV:-16}
PLAY=hw:$card,$PLAY_DEV
CAP=hw:$card,$CAP_DEV
# the device nodes behind them, to find who holds one that is busy
PLAY_NODE=/dev/snd/pcmC${card}D${PLAY_DEV}p
CAP_NODE=/dev/snd/pcmC${card}D${CAP_DEV}c
# A short wait. OpenWrt's busybox sleep takes whole seconds only ("sleep 0.1" is an error there and returns at
# once, which turned every wait loop below into a busy loop): fractions where sleep takes them, else usleep, else
@@ -118,6 +121,105 @@ mask() {
}
log() { echo "mu300-voice: $*" | mask; }
# --- the programs this run starts, and nothing left behind ----------------------------------------------------
# A melody or an echo is an aplay/arecord holding a voice PCM. Run in the foreground, a TERM to this script (or its
# ^C) ended the script and left the aplay running on its own: the next "mu300-voice call" then failed with "audio
# open error: Resource busy", for the melody and the echo (docs/FINDINGS.md 188). And a shell runs its trap only
# after the foreground command returns, so a trap alone would not have helped. Every such program is started in
# the background and waited for (child), which a signal interrupts at once; the trap then ends each one and waits
# until it has gone, so its PCM is closed before the script exits.
# Ending one is only a close of the PCM (drop and free), never a PREPARE + START on a stream that stopped: on 5.4 a
# voice stream restarted after an xrun panics the kernel (docs/FINDINGS.md 24e), and nothing here restarts one.
CHILDREN=
SCENE_STARTING=
alive() { # alive PID: running, not a zombie that is only waiting to be reaped
kill -0 "$1" 2>/dev/null || return 1
[ -r "/proc/$1/stat" ] || return 0
case $(sed 's/^.*) //' "/proc/$1/stat" 2>/dev/null | cut -c1) in Z|X|'') return 1 ;; esac
return 0
}
reap() { # reap PID: TERM, up to 3 s to close its PCM and go, then KILL
kill "$1" 2>/dev/null
_n=0
while alive "$1" && [ "$_n" -lt 30 ]; do nap 0.1; _n=$((_n + 1)); done
alive "$1" && kill -9 "$1" 2>/dev/null
return 0
}
child() { # child COMMAND... - run it as a child this script ends when it is ended
"$@" &
_c=$!
CHILDREN="$CHILDREN $_c"
wait "$_c"; _rc=$?
CHILDREN=$(echo "$CHILDREN" | sed "s/ $_c\$//; s/ $_c / /")
return "$_rc"
}
cleanup() {
for _p in $CHILDREN; do reap "$_p"; wait "$_p" 2>/dev/null; done
CHILDREN=
# a call scene this run was still starting: stopped, its controls put back. One that started is the call's
# and stays (audio stop, hangup), as it always has.
if [ -n "$SCENE_STARTING" ]; then SCENE_STARTING=; audio_stop >/dev/null 2>&1; fi
}
on_signal() { trap - EXIT; cleanup; exit "$1"; }
guard_children() {
trap cleanup EXIT
trap 'on_signal 129' HUP
trap 'on_signal 130' INT
trap 'on_signal 143' TERM
}
# Who holds a PCM node: pids with an open descriptor on it, from /proc (one ls, no fuser on OpenWrt's busybox).
pcm_holders() {
ls -l /proc/[0-9]*/fd 2>/dev/null | awk -v n="$1" '
/^\/proc\/[0-9]+\/fd:$/ { split($0, a, "/"); pid = a[3]; next }
$NF == n && pid != "" { print pid }' | sort -u
}
# A PCM that is busy: say who has it. An aplay/arecord playing or recording one of this script's own files is left
# over from a mu300-voice that was killed before this one cleaned up after itself, and is ended; anything else is
# only reported. 0 when something was ended (worth one more try).
pcm_busy() { # pcm_busy NODE
_freed=1
for _p in $(pcm_holders "$1"); do
[ "$_p" = "$$" ] && continue
_comm=$(cat "/proc/$_p/comm" 2>/dev/null)
_cmd=$(tr '\0' ' ' < "/proc/$_p/cmdline" 2>/dev/null)
case "$_comm:$_cmd" in
aplay:*"$TMP/"*|arecord:*"$TMP/"*)
echo "mu300-voice: $1 is held by pid $_p ($_comm), left over from an earlier mu300-voice: ending it" >&2
reap "$_p"; _freed=0 ;;
*)
echo "mu300-voice: $1 is held by pid $_p (${_comm:-?}); stop it, or run mu300-voice audio stop" >&2 ;;
esac
done
return "$_freed"
}
# pcm_run ERRFILE NODE COMMAND... - an aplay/arecord on a voice PCM, as a child, its errors in ERRFILE. One more
# try, and only for an open that failed (a fresh open: hw_params, prepare and start of a new stream, never a restart
# of a stopped one):
# * busy, and pcm_busy ended a leftover of ours;
# * EIO: the stream's STARTUP failed in the driver, which read DSP replies nobody had waited for as the answer to
# it ("Haven't got right cmd(0x4), got cmd(0x9)"): every play into FE_ST_VOICE_PCM_P leaves two, and five fail
# the next FE_ST_DUMP open. Each try reads five, so the next open works. The driver now drops such replies
# itself (audio-sipc, docs/FINDINGS.md 188); this covers a kernel without that.
pcm_run() {
_err=$1; _node=$2; shift 2
_try=0
while :; do
child "$@" 2>"$_err" && return 0
_rc=$?
[ "$_try" = 0 ] || return "$_rc"
_try=1
if grep -q 'audio open error:.*[Bb]usy' "$_err" 2>/dev/null; then
pcm_busy "$_node" || return "$_rc"
elif grep -q 'audio open error: Input/output error' "$_err" 2>/dev/null; then
echo "mu300-voice: $_node: the DSP refused the open (EIO), trying once more" >&2
else
return "$_rc"
fi
nap 0.5
done
}
# --- mixer, with an undo log ---------------------------------------------------------------------------------
# Every control the call touches is read before its first write and put back by "audio stop", so a call leaves
# the card exactly as it found it (the E5 port does the same). Raw controls (profile selects, VBC_VOLUME) go
@@ -261,14 +363,16 @@ audio_start() { # audio_start OUTPUT
routes "$out"
mute_dl
# both directions of the hostless scene, prepared together and then started (pcmhost does that order)
SCENE_STARTING=1
pcmhost "/dev/snd/pcmC${card}D${VOICE}p,/dev/snd/pcmC${card}D${VOICE}c" "$RATE" 1 0 > "$TMP/scene.log" 2>&1 &
echo $! > "$SCENE_PID"
n=0
while ! grep -q '^started' "$TMP/scene.log" 2>/dev/null; do
scene_running || { log "the call scene did not start: $(tail -1 "$TMP/scene.log")" >&2; audio_stop; return 1; }
n=$((n + 1)); [ "$n" -gt 50 ] && { log "the call scene did not start in 5 s" >&2; audio_stop; return 1; }
scene_running || { log "the call scene did not start: $(tail -1 "$TMP/scene.log")" >&2; SCENE_STARTING=; audio_stop; return 1; }
n=$((n + 1)); [ "$n" -gt 50 ] && { log "the call scene did not start in 5 s" >&2; SCENE_STARTING=; audio_stop; return 1; }
nap 0.1
done
SCENE_STARTING=
# the vendor applies the parameters again once both directions run - and the Bluetooth rate again too, which
# only takes after the scene is RUNNING (kanoqwq/e5-linux FINDINGS 59: set before, the BT side ran 3x slow)
profiles "$out"
@@ -417,13 +521,14 @@ voice_play() { # voice_play FILE -> play it into the call, trying each framing
for p in $PERIODS; do
ps=${p%,*}; bs=${p#*,}
if [ "$ps" = 0 ]; then
err=$(aplay -D "$PLAY" -f S16_LE -r "$PLAY_RATE" -c 1 -q "$f" 2>&1)
pcm_run "$TMP/play.err" "$PLAY_NODE" aplay -D "$PLAY" -f S16_LE -r "$PLAY_RATE" -c 1 -q "$f"
else
# scale the framing if the rate is not the 8k these numbers were written for
ps=$((ps * PLAY_RATE / 8000)); bs=$((bs * PLAY_RATE / 8000))
err=$(aplay -D "$PLAY" -f S16_LE -r "$PLAY_RATE" -c 1 -q \
--period-size="$ps" --buffer-size="$bs" "$f" 2>&1)
pcm_run "$TMP/play.err" "$PLAY_NODE" aplay -D "$PLAY" -f S16_LE -r "$PLAY_RATE" -c 1 -q \
--period-size="$ps" --buffer-size="$bs" "$f"
fi
err=$(cat "$TMP/play.err" 2>/dev/null)
[ -z "$err" ] && { echo "$ps,$bs" > "$TMP/framing"; return 0; }
last=$err
done
@@ -461,11 +566,11 @@ echo_loop() {
uplink_conf
while :; do
# the downlink from the dump (48 kHz, two equal channels), converted by plug to the uplink's 16 kHz mono
arecord -D "$CAP" -f S16_LE -r 48000 -c 2 -d "$secs" -q \
--period-size=960 --buffer-size=3840 "$TMP/echo.raw" 2>"$TMP/cap.err" || {
pcm_run "$TMP/cap.err" "$CAP_NODE" arecord -D "$CAP" -f S16_LE -r 48000 -c 2 -d "$secs" -q \
--period-size=960 --buffer-size=3840 "$TMP/echo.raw" || {
echo "mu300-voice: capture failed: $(head -1 "$TMP/cap.err")" >&2; return 1; }
ALSA_CONFIG_PATH=$TMP/uplink.conf aplay -D mu300_uplink -f S16_LE -r 48000 -c 2 -q \
--period-time=20000 --buffer-time=120000 "$TMP/echo.raw" 2>"$TMP/play.err" || {
pcm_run "$TMP/play.err" "$PLAY_NODE" env ALSA_CONFIG_PATH="$TMP/uplink.conf" aplay -D mu300_uplink \
-f S16_LE -r 48000 -c 2 -q --period-time=20000 --buffer-time=120000 "$TMP/echo.raw" || {
echo "mu300-voice: playback failed: $(head -1 "$TMP/play.err")" >&2; return 1; }
done
}
@@ -480,6 +585,10 @@ demo() {
echo_loop "${1:-5}"
}
case "${1:-status}" in
answer|call|demo|tone|echo|audio) guard_children ;;
esac
case "${1:-status}" in
audio)
case "${2:-}" in
+315
View File
@@ -0,0 +1,315 @@
"""A killed mu300-voice leaves nothing behind, and a DSP reply left over from it does not fail the next open
(docs/FINDINGS.md 188).
* mu300-voice runs every aplay/arecord as a child it ends on TERM/INT/HUP/exit, finds and ends a leftover of an
earlier run that holds a voice PCM, and opens a PCM once more after EIO.
* audio-sipc's aud_recv_cmd() drops a reply for another command and waits on within the same timeout: compiled here
against a fake message cache (the same function in the mainline tree and in the 5.4 patch)."""
import os
import re
import shutil
import signal
import subprocess
import tempfile
import time
import unittest
from pathlib import Path
from helpers import TOP
VOICE = TOP / 'rootfs' / 'overlay' / 'opt' / 'mu300' / 'bin' / 'mu300-voice'
SIPC = TOP / 'upstream' / 'modules' / 'sprd_audio' / 'sprd_audio' / 'audiosipc' / 'audio-sipc.c'
PATCH54 = TOP / 'kernel' / 'patches' / 'audio-sipc-stale-reply.patch'
BUILD_AUDIO = TOP / 'kernel' / 'build-audio.sh'
def func(src, name):
m = re.search(r'(?ms)^%s\(\) \{[^\n]*\n.*?\n\}\n' % re.escape(name), src)
if not m:
m = re.search(r'(?m)^%s\(\) \{.*\}$' % re.escape(name), src)
assert m, name
return m.group(0).rstrip('\n') + '\n'
def voice_lib(*names, audio_stop='audio_stop() { echo stopped >> "$TMP/stop.log"; }\n'):
src = VOICE.read_text()
return ('nap() { sleep "$1"; }\n' + audio_stop +
''.join(func(src, n) for n in names))
CHILD_FUNCS = ('alive', 'reap', 'child', 'cleanup', 'on_signal', 'guard_children')
def gone(pid):
try:
os.kill(pid, 0)
except ProcessLookupError:
return True
try:
state = Path('/proc/%d/stat' % pid).read_text().rsplit(') ', 1)[1][0]
return state in 'ZX'
except OSError:
return False
class Children(unittest.TestCase):
"""The orphaned `aplay -D mu300_uplink` of the owner's test call: a signal to the script ends its players."""
def run_and_signal(self, sig, starting=False):
with tempfile.TemporaryDirectory() as d:
pidf = Path(d) / 'player.pid'
script = ('TMP=%s\nCHILDREN=\nSCENE_STARTING=%s\n' % (d, '1' if starting else '') +
voice_lib(*CHILD_FUNCS) +
'guard_children\n'
# a player that holds on like aplay on a stalled PCM: its pid, then a long wait
'child sh -c \'echo $$ > %s; exec sleep 60\'\n'
'echo returned\n' % pidf)
p = subprocess.Popen(['sh', '-c', script], stdout=subprocess.PIPE, text=True)
for _ in range(100):
if pidf.exists() and pidf.read_text().strip():
break
time.sleep(0.05)
player = int(pidf.read_text())
t0 = time.time()
p.send_signal(sig)
out, _ = p.communicate(timeout=10)
took = time.time() - t0
try:
self.assertTrue(gone(player), 'the player outlived the script')
finally:
if not gone(player):
os.kill(player, signal.SIGKILL)
self.assertNotIn('returned', out)
self.assertLess(took, 5)
stopped = (Path(d) / 'stop.log').exists()
return p.returncode, stopped
def test_term_ends_the_player(self):
rc, stopped = self.run_and_signal(signal.SIGTERM)
self.assertEqual(rc, 143)
self.assertFalse(stopped, 'a scene that had started is the call\'s and stays')
def test_int_and_hup_too(self):
self.assertEqual(self.run_and_signal(signal.SIGINT)[0], 130)
self.assertEqual(self.run_and_signal(signal.SIGHUP)[0], 129)
def test_a_scene_still_starting_is_stopped(self):
rc, stopped = self.run_and_signal(signal.SIGTERM, starting=True)
self.assertTrue(stopped)
def test_child_returns_the_status_and_forgets_the_pid(self):
script = ('CHILDREN=\n' + voice_lib(*CHILD_FUNCS) +
'child sh -c "exit 3"; echo "rc=$? [$CHILDREN]"\n'
'child true; echo "rc=$? [$CHILDREN]"\n')
out = subprocess.run(['sh', '-c', script], capture_output=True, text=True, check=True).stdout
self.assertEqual(out.split('\n')[:2], ['rc=3 []', 'rc=0 []'])
def test_every_player_goes_through_pcm_run(self):
src = VOICE.read_text()
code = '\n'.join(l for l in src.splitlines() if not l.lstrip().startswith('#'))
for m in re.finditer(r'.*\b(aplay|arecord) -D.*', code):
self.assertIn('pcm_run ', m.group(0), m.group(0))
self.assertNotIn('err=$(aplay', code)
# the commands that start players install the guard first
self.assertRegex(src, r'answer\|call\|demo\|tone\|echo\|audio\) guard_children ;;')
# and the scene's own start is marked, so a signal in the middle of it puts the controls back
body = func(src, 'audio_start')
self.assertLess(body.index('SCENE_STARTING=1'), body.index('pcmhost "'))
self.assertIn(' SCENE_STARTING=\n', body)
def test_nothing_restarts_a_stopped_stream(self):
# 5.4 panics on PREPARE + START after an xrun (FINDINGS 24e): ending a player is TERM (it closes its PCM),
# and a retry is a fresh open, only after an open error
body = func(VOICE.read_text(), 'pcm_run')
self.assertIn("'audio open error: Input/output error'", body)
self.assertIn("'audio open error:.*[Bb]usy'", body)
self.assertNotIn('Input/output error\'"', body.replace("'audio open error: Input/output error'", ''))
class Retry(unittest.TestCase):
def run_pcm_run(self, errors, busy_frees=False):
"""errors: what each try of the fake player prints (empty: success)."""
with tempfile.TemporaryDirectory() as d:
for i, e in enumerate(errors):
(Path(d) / ('err%d' % i)).write_text(e)
player = Path(d) / 'player'
player.write_text('#!/bin/sh\nn=$(cat %s/n 2>/dev/null || echo 0); echo $((n + 1)) > %s/n\n'
'e=$(cat %s/err$n 2>/dev/null); [ -z "$e" ] && exit 0; echo "$e" >&2; exit 1\n'
% (d, d, d))
player.chmod(0o755)
script = ('CHILDREN=\nTMP=%s\n' % d + voice_lib(*CHILD_FUNCS) +
'pcm_busy() { echo "busy $1" >&2; %s; }\n' % ('return 0' if busy_frees else 'return 1') +
func(VOICE.read_text(), 'pcm_run') +
'pcm_run %s/e /dev/snd/pcmC0D53p %s; echo "rc=$?"\n' % (d, player))
r = subprocess.run(['sh', '-c', script], capture_output=True, text=True)
tries = int((Path(d) / 'n').read_text())
return r.stdout.strip(), tries, r.stderr
def test_eio_at_open_is_tried_once_more(self):
out, tries, err = self.run_pcm_run(['arecord: main:831: audio open error: Input/output error', ''])
self.assertEqual((out, tries), ('rc=0', 2))
self.assertIn('trying once more', err)
def test_only_once(self):
eio = 'arecord: main:831: audio open error: Input/output error'
out, tries, _ = self.run_pcm_run([eio, eio, ''])
self.assertEqual((out, tries), ('rc=1', 2))
def test_an_error_after_the_open_is_not_retried(self):
out, tries, _ = self.run_pcm_run(['aplay: pcm_write:2146: write error: Input/output error', ''])
self.assertEqual((out, tries), ('rc=1', 1))
def test_busy_retried_only_when_a_leftover_was_ended(self):
busy = 'aplay: main:831: audio open error: Device or resource busy'
out, tries, err = self.run_pcm_run([busy, ''], busy_frees=False)
self.assertEqual((out, tries), ('rc=1', 1))
self.assertIn('busy /dev/snd/pcmC0D53p', err)
out, tries, _ = self.run_pcm_run([busy, ''], busy_frees=True)
self.assertEqual((out, tries), ('rc=0', 2))
@unittest.skipUnless(Path('/proc/self/fd').is_dir() and shutil.which('sleep'), 'needs Linux /proc')
class Holders(unittest.TestCase):
"""pcm_holders/pcm_busy find who has the node open; only a player of this script's own files is ended."""
def test_leftover_ended_stranger_only_reported(self):
with tempfile.TemporaryDirectory() as d:
tmp = Path(d) / 'run'
(tmp / 'bin').mkdir(parents=True)
node = Path(d) / 'pcmC0D53p'
node.write_text('')
# an "aplay" whose command line names a file of ours, and a stranger holding the same node
aplay = tmp / 'bin' / 'aplay'
shutil.copy(shutil.which('sleep'), aplay)
with open(node) as f1, open(node) as f2:
ours = subprocess.Popen([str(aplay), '60'], stdin=f1)
stranger = subprocess.Popen(['sleep', '60'], stdin=f2)
try:
time.sleep(0.2)
script = ('TMP=%s\n' % tmp + voice_lib('alive', 'reap', 'pcm_holders', 'pcm_busy') +
'pcm_holders %s | tr "\\n" " "; echo\npcm_busy %s; echo "rc=$?"\n' % (node, node))
r = subprocess.run(['sh', '-c', script], capture_output=True, text=True, timeout=20)
holders = r.stdout.splitlines()[0].split()
self.assertEqual(sorted(holders), sorted([str(ours.pid), str(stranger.pid)]))
self.assertIn('rc=0', r.stdout)
self.assertIn('left over from an earlier mu300-voice: ending it', r.stderr)
self.assertIn('held by pid %d (sleep)' % stranger.pid, r.stderr)
ours.wait(timeout=5)
self.assertIsNone(stranger.poll())
finally:
for p in (ours, stranger):
if p.poll() is None:
p.kill()
p.wait()
FAKE = r'''
#include <errno.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
typedef uint8_t u8; typedef uint16_t u16; typedef uint32_t u32;
#define AUD_IPC_AGDSP 0
#define SMSG_CACHE_NR 256
#define pr_warn(...) do { } while (0)
#define pr_err(...) do { } while (0)
#define sp_asoc_pr_dbg(...) do { } while (0)
struct aud_smsg { uint16_t command; uint16_t channel; u32 parameter0, parameter1, parameter2, parameter3; };
static void aud_smsg_set(struct aud_smsg *m, uint16_t ch, uint16_t cmd, u32 a, u32 b, u32 c, int d)
{ m->channel = ch; m->command = cmd; m->parameter0 = a; m->parameter1 = b; m->parameter2 = c; m->parameter3 = d; }
/* the channel's cache: messages with the jiffy they arrive at */
static unsigned long jiffies;
static struct { u16 cmd; unsigned long at; } q[400];
static int qn, qr, waits[64], nwaits;
static void put(u16 cmd, unsigned long at) { q[qn].cmd = cmd; q[qn].at = at; qn++; }
static int aud_smsg_recv(u8 dst, struct aud_smsg *msg, int timeout)
{
if (timeout > 0 && nwaits < 64) waits[nwaits++] = timeout;
if (qr < qn && (q[qr].at <= jiffies || timeout < 0 ||
(timeout > 0 && q[qr].at <= jiffies + (unsigned long)timeout))) {
if (q[qr].at > jiffies) jiffies = q[qr].at;
msg->command = q[qr].cmd; msg->parameter3 = qr; qr++;
return 0;
}
if (timeout == 0) return -ENODATA;
jiffies += timeout; /* the real one also resets the DSP here */
return -ETIME;
}
static void reset(void) { jiffies = 1000; qn = qr = nwaits = 0; }
'''
MAIN = r'''
#define CH 1
#define CHECK(c) do { if (!(c)) { printf("FAIL %d: %s\n", __LINE__, #c); return 1; } } while (0)
int main(void)
{
struct aud_smsg r;
int i;
/* the drain before a send: a stale KCTL_SET reply no longer stops it, a STARTUP reply is returned */
reset(); put(9, 0); put(4, 0);
CHECK(aud_recv_cmd(CH, 4, &r, 0) == 0 && r.command == 4 && r.parameter3 == 1);
reset(); put(9, 0); put(9, 0); put(9, 0);
CHECK(aud_recv_cmd(CH, 4, &r, 0) == -ENODATA && qr == 3);
/* the wait: the stale reply is dropped and the wait goes on with what is left of the timeout */
reset(); put(9, 1100); put(4, 1200);
CHECK(aud_recv_cmd(CH, 4, &r, 300) == 0 && r.command == 4);
CHECK(nwaits == 2 && waits[0] == 300 && waits[1] == 200 && jiffies == 1200);
/* and never longer than the timeout in all */
reset(); put(9, 1100); put(4, 1500);
CHECK(aud_recv_cmd(CH, 4, &r, 300) == -EIO);
CHECK(jiffies <= 1000 + 300 + 1);
/* a deadline already passed while a stale reply was read: still a real wait of one jiffy, never 0 */
reset(); put(9, 1300);
CHECK(aud_recv_cmd(CH, 4, &r, 300) == -EIO && waits[1] == 1);
/* the plain case is unchanged */
reset(); put(5, 1010);
CHECK(aud_recv_cmd(CH, 5, &r, 300) == 0 && r.command == 5 && nwaits == 1);
/* waiting forever (-1) skips a stale reply the same way */
reset(); put(9, 2000); put(4, 3000);
CHECK(aud_recv_cmd(CH, 4, &r, -1) == 0 && r.command == 4);
/* a cache full of the wrong replies ends, it does not spin */
reset(); for (i = 0; i < 300; i++) put(9, 0);
CHECK(aud_recv_cmd(CH, 4, &r, 0) == -EIO && qr == SMSG_CACHE_NR);
puts("ok");
return 0;
}
'''
def recv_cmd(src):
m = re.search(r'(?ms)^int aud_recv_cmd\(.*?\n\}\n', src)
assert m
return m.group(0)
class StaleReply(unittest.TestCase):
def test_same_function_in_both_trees(self):
# the 5.4 patch adds exactly the mainline function
patched = '\n'.join(l[1:] for l in PATCH54.read_text().splitlines()
if l.startswith(('+', ' ')) and not l.startswith('+++'))
self.assertEqual(recv_cmd(patched + '\n'), recv_cmd(SIPC.read_text()))
self.assertIn('audio-sipc-stale-reply:dropped:sprd_audio/audiosipc', BUILD_AUDIO.read_text())
self.assertNotRegex(PATCH54.read_text(), r'\bSIP\b|[Gg]ateway')
@unittest.skipUnless(shutil.which('cc'), 'needs a C compiler')
def test_aud_recv_cmd(self):
with tempfile.TemporaryDirectory() as d:
c = Path(d) / 't.c'
c.write_text(FAKE + recv_cmd(SIPC.read_text()) + MAIN)
subprocess.run(['cc', '-Wall', '-Werror', '-o', str(Path(d) / 't'), str(c)], check=True,
capture_output=True)
r = subprocess.run([str(Path(d) / 't')], capture_output=True, text=True)
self.assertEqual((r.returncode, r.stdout.strip()), (0, 'ok'), r.stdout)
if __name__ == '__main__':
unittest.main()
@@ -23,6 +23,7 @@
#include <linux/firmware.h>
#include <linux/init.h>
#include <linux/io.h>
#include <linux/jiffies.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/of.h>
@@ -519,41 +520,65 @@ int aud_ipc_ch_close(uint16_t channel)
}
EXPORT_SYMBOL(aud_ipc_ch_close);
/*
* Replies on a channel are read in order, and some are never waited for: the voice PCM tap's trigger and shutdown
* send a KCTL_SET (cmd 9) with aud_send_cmd_no_wait_param() and the DSP answers each anyway, and a sender whose
* wait was interrupted leaves its reply too. They stay in the channel's cache. The drain before a send stopped at
* the first reply for another command, and each of the 4 tries of the wait read one more, so with 5 of them
* queued a STARTUP (cmd 4) failed with "Haven't got right cmd(0x4), got cmd(0x9)" and -EIO, and so did the PCM
* open behind it: FE_ST_DUMP right after a few plays into FE_ST_VOICE_PCM_P. A reply for another command is now
* dropped and the wait goes on for the right one, within the same timeout; with timeout 0 (the drain) it reads on
* until the cache is empty.
*/
int aud_recv_cmd(u16 channel, u32 cmd, struct aud_smsg *result,
int32_t timeout)
{
int ret = 0;
int dropped = 0;
unsigned long deadline = jiffies + (timeout > 0 ? timeout : 0);
struct aud_smsg mrecv = { 0 };
aud_smsg_set(&mrecv, channel, cmd, 0, 0, 0, 0);
for (;;) {
int32_t wait = timeout;
ret = aud_smsg_recv(AUD_IPC_AGDSP, &mrecv, timeout);
if (ret < 0) {
if (-ENODATA == ret) {
pr_warn("%s channel =%u cmd=%u ENODATA\n",
__func__, channel, cmd);
return ret;
if (timeout > 0) {
long left = (long)(deadline - jiffies);
/* never 0, which would mean "do not wait" to aud_smsg_recv */
wait = left > 0 ? (int32_t)left : 1;
}
pr_err("%s, Failed to recv channel =%d cmd(0x%x),ret(%d)\n",
__func__, channel, cmd, ret);
return -EIO;
}
sp_asoc_pr_dbg("%s, chan: 0x%x, cmd: 0x%x, value0: 0x%x, value1: 0x%x,",
__func__, mrecv.channel, mrecv.command,
mrecv.parameter0, mrecv.parameter1);
sp_asoc_pr_dbg(" value2: 0x%x, value3: 0x%x, timeout: %d\n",
mrecv.parameter2, mrecv.parameter3, timeout);
aud_smsg_set(&mrecv, channel, cmd, 0, 0, 0, 0);
if (cmd == mrecv.command && mrecv.channel == channel && result) {
*result = mrecv;
return 0;
}
pr_err("%s, Haven't got right cmd(0x%x), got cmd(0x%x)",
__func__, cmd, mrecv.command);
pr_err(" got chan(0x%x)\n",
mrecv.channel);
ret = aud_smsg_recv(AUD_IPC_AGDSP, &mrecv, wait);
if (ret < 0) {
if (-ENODATA == ret) {
pr_warn("%s channel =%u cmd=%u ENODATA\n",
__func__, channel, cmd);
return ret;
}
pr_err("%s, Failed to recv channel =%d cmd(0x%x),ret(%d)\n",
__func__, channel, cmd, ret);
return -EIO;
}
sp_asoc_pr_dbg("%s, chan: 0x%x, cmd: 0x%x, value0: 0x%x, value1: 0x%x,",
__func__, mrecv.channel, mrecv.command,
mrecv.parameter0, mrecv.parameter1);
sp_asoc_pr_dbg(" value2: 0x%x, value3: 0x%x, timeout: %d\n",
mrecv.parameter2, mrecv.parameter3, timeout);
return -EIO;
if (cmd == mrecv.command && mrecv.channel == channel) {
if (result)
*result = mrecv;
return 0;
}
pr_warn("%s, dropped a stale reply: cmd(0x%x) chan(0x%x) while waiting for cmd(0x%x)\n",
__func__, mrecv.command, mrecv.channel, cmd);
if (++dropped >= SMSG_CACHE_NR) {
pr_err("%s, Haven't got right cmd(0x%x) in %d replies\n",
__func__, cmd, dropped);
return -EIO;
}
}
}
static int aud_send_msg(u16 channel, u32 cmd, u32 value0,