Repository navigation
ASoC: apple: source TAS5770L amp gain from the boot device tree - #3385
RyanTheTide wants to merge 5 commits into
Conversation
Document the optional row copied by the Apple bootloader for each TAS5770L speaker amplifier. The row describes the analog operating gain and names the source format's slot fields. Signed-off-by: Ryan Murray <ryan@aurorasilicon.org>
The bootloader can hand the machine's speaker-config row to each amp. Read that row before adding the speaker backend and apply the decoded gain to its mixer control through the existing per-amp volume limiter. Skip the TAS speaker backend if any row is absent or unusable. Share the codec register range with the driver. Reject zero because the ASoC volume platform limit uses zero to indicate no limit. Keep the SN012776 fixed-ceiling check and Linux's TAS sense layout. Signed-off-by: Ryan Murray <ryan@aurorasilicon.org>
There was a problem hiding this comment.
Verdict: FINISH, then merge at 37cf5963 (draft until the physical TAS5770L row and aura #542 land)
Blockers: none.
Checked:
- Complete-group admission holds.
macaudio_amp_level_count()returns 0 as soon as anysound-daiamp has no row, a malformed row or a level that is not allowed, so a partly written group never opens the speakers. - Zero is refused (
level > 0), because a zero platform maximum means no limit to ASoC. Anything aboveTAS2770_AMP_GAIN_MAX(0x14, now shared with the codec's control) is refused, and so is a node that is notti,tas5770l. - The fixed-ceiling check for SN012776 is unchanged: same mask, same maximum,
macaudio_amp_level_allowed()is only renamed. - With an older loader (no rows),
macaudio_parse_of()skips the speaker link before the BEs are filled. The TAS components are then not on the card,macaudio_limit_amp_levels()finds none (count 0 ==tas_amp_count0), and the jack and microphone links still register. - With rows, every TAS component on the card must be limited, or probe fails:
count != tas_amp_countgives an error. - The value is the machine's own. The J313 ADT (
reference/adt/gravity-adt-collection/27.0.1/t8103-j313.txt) hasamp_gain = 10in both rows ofaudio-tas5770L-spkr-l'sspeaker-config, the same as the10this PR removes frommacaudio_j313_cfg, and as a raw byte with no flag bits. So reading the byte unmasked is right for TAS5770L.
No board gate is added, three per-board constants are removed. No Apple material, no attribution.
Evidence and notes
- Read at
37cf5963: the fullmacaudio.cdiff,macaudio_parse_of()around lines 2690-2775,tas2770.c/tas2770.h, and the binding.ti,sn012776lives inti,tas27xx.yaml, so the newapple,speaker-config: falsefor non-TAS5770L compatibles inti,tas2770.yamldoes not touch SN012776 nodes. - Not yet compared: J274 and J293 ADT rows are not in our ADT collection, so I could not check them against the removed caps (20 and 15). The ADT is the authority either way. When the physical or archived rows come in, note in the PR if either differs, because that changes the live cap on that model.
- Not run: no KUnit or hardware here. This review is source plus the ADT cross-check.
Conflict in macaudio-amp-level-test.h: main added macaudio_j775_cfg to macaudio_level_no_table(), which checks the per-board amp_gain field. This branch removes that field and the test with it, so keep this side; the new J775 cfg carries no amp gain.
|
Silent TAS5770L row harness (no PCM opened). For the J313 one-shot rows of this PR (head The probe binds the ALSA card to the live DT sound node. It checks every TAS amp's Modes: Run: sha256 check-tas-row.py#!/usr/bin/env python3
"""Read the live amp handoff and ALSA control limits without opening a PCM."""
import argparse
import json
import os
from pathlib import Path
import re
import subprocess
import sys
from types import ModuleType
DT = Path("/proc/device-tree")
TAS = "ti,tas5770l"
GAIN = "Amp Gain Volume"
PROTECTION = "Speaker Protection"
def amixer(card, *args):
return subprocess.check_output(
["amixer", "-i", "-c", str(card), *args], encoding="utf-8", timeout=10,
env={**os.environ, "LC_ALL": "C"}, stderr=subprocess.DEVNULL,
)
def mixer_controls(output):
controls = {}
for line in output.splitlines():
item = re.fullmatch(r"numid=(\d+),iface=MIXER,name='([^']+)'(?:,.*)?", line)
if not item:
continue
numid, name = item.groups()
controls.setdefault(name, []).append(numid)
return controls
def gain_maximum(output):
# amixer cget gets element info and may also print current values. Only
# the raw control maximum is relevant, before or after a lease grant.
match = re.search(r"^ *; type=INTEGER,.*\bmax=(\d+)(?:,|$)", output, re.MULTILINE)
if match is None:
raise ValueError("no integer maximum in ALSA control info")
return int(match[1])
def check_row(wiring, dt, expect):
hw = wiring.read_dt(str(dt))
codecs = wiring._speaker_link(hw)["codecs"]
tas = [codec for codec in codecs if TAS in codec["compatible"]]
if not codecs or (tas and len(tas) != len(codecs)):
raise ValueError("empty or mixed speaker codec group")
if bool(tas) != (expect != "reference"):
raise ValueError("speaker codec family does not match the requested row")
card = wiring.live_card(hw, dt=str(dt))
if card is None:
raise ValueError("the DT speaker card is not registered")
index, card_id = card
# In legacy-interface mode the lease control can exist but be inactive.
controls = mixer_controls(amixer(index, "controls"))
if len(controls.get(PROTECTION, [])) != (0 if expect == "refused" else 1):
raise ValueError("unexpected number of Speaker Protection controls")
gains = set()
matched = 0
rows = 0
for codec in tas:
name = f"{codec.get('prefix', '')} {GAIN}".lstrip()
if name in gains:
raise ValueError("ambiguous amp gain control prefix")
gains.add(name)
path = dt / codec["node"] / "apple,speaker-config"
try:
row = path.read_bytes()
except FileNotFoundError:
row = b""
# The exported ABI is four bytes with the level in byte 1.
if len(row) == 4 and row[1] > 0:
rows += 1
ids = controls.get(name, [])
if expect == "refused":
if ids:
raise ValueError(f"{name} is exposed on a refused speaker route")
continue
if len(row) != 4 or row[1] == 0:
raise ValueError("missing, malformed or zero TAS gain row")
if len(ids) != 1 or gain_maximum(amixer(index, "cget", f"numid={ids[0]}")) != row[1]:
raise ValueError(f"{name} maximum does not match its DT row")
matched += 1
actual = {name for name in controls if name == GAIN or name.endswith(f" {GAIN}")}
if tas and actual != (gains if expect == "present" else set()):
raise ValueError("unexpected set of TAS amp gain controls")
if expect == "refused" and rows == len(tas):
raise ValueError("refusal row does not demonstrate a missing, malformed or zero gain")
jack_prefixes = {
codec["prefix"]
for link in hw["links"] if link["name"] == "Headphone Jack"
for codec in link["codecs"] if codec.get("prefix")
}
jack_controls = sorted(
name for name in controls if any(name.startswith(f"{prefix} ") for prefix in jack_prefixes)
)
if jack_prefixes and not jack_controls:
raise ValueError("companion jack controls named by DT are missing")
return {
"board": hw["board"],
"card": card_id,
"speaker_codecs": [codec["compatible"][0] for codec in codecs],
"route": expect,
"tas_gain_maxima_matched": matched,
"readable_nonzero_tas_rows": rows,
"jack_controls": jack_controls,
"playback_calls": 0,
}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("wiring", type=Path, help="path to speakerguardd's wiring.py")
parser.add_argument("--expect", choices=("present", "refused", "reference"), required=True)
parser.add_argument("--kernel-release", required=True)
parser.add_argument("--stage2-version", required=True)
args = parser.parse_args()
boot = Path("/proc/sys/kernel/random/boot_id")
sys.dont_write_bytecode = True
try:
boot_id = boot.read_text()
kernel = os.uname().release
stage2 = (DT / "chosen/asahi,m1n1-stage2-version").read_bytes().rstrip(b"\0").decode()
if kernel != args.kernel_release or stage2 != args.stage2_version:
raise ValueError(f"expected build differs from live kernel {kernel} or Stage 2 {stage2}")
# Accept a pinned checkout file or a stream from a shell descriptor.
wiring = ModuleType("wiring")
wiring.__file__ = str(args.wiring)
exec(compile(args.wiring.read_bytes(), wiring.__file__, "exec"), vars(wiring))
try:
result = check_row(wiring, DT, args.expect)
except wiring.Refused as error:
raise ValueError(str(error)) from error
if boot.read_text() != boot_id:
raise ValueError("boot identity changed during the probe")
print(json.dumps({"kernel": kernel, "stage2": stage2, **result}, sort_keys=True))
except (OSError, ValueError, subprocess.SubprocessError) as error:
print(f"FAIL: {error}", file=sys.stderr)
return 1
return 0
if __name__ == "__main__":
sys.exit(main()) |
|
Silent regression rows, SN012776 macaudio: J473 (M2 mini) and J413 (M2 Air). Both PASS. Candidate: fleet89 (
Both Macs are back on saved fleet89 (taint 4 = baseline, v2 active, Enforcing). The TAS5770L rows (refused on the current Stage 2, present with aura#542) are queued on erikwb's J313 through aurora-agents (owner standing approval, silent). The probe is in the comment above. |
Main added a v2-only DC-blocker requirement to the SN012776 level check (now a bool helper) and its KUnit case. This branch generalises the same helper to count SN012776 and TAS5770L amps. Keep the counting helper and fold main's DC-blocker check into it, keep both sets of KUnit fixtures and cases, and take main's tweeter high-pass comment. Main's no_table test checks the per-board amp_gain field this branch removes, so it stays dropped.
|
|
|
Ready for review, merging with a filed known gap (#3654). This follows the standing rules: don't block on testers who haven't agreed, and merge, then fix the known gap.
|
There was a problem hiding this comment.
Verdict: MERGE at e3d44558
Blockers: None (physical TAS5770L J313 confirmation is tracked as a filed known gap in #3654 under fail-closed admission; the red host-tests job is the pre-existing main apple-scaler-recovery-tests stub failure).
Checked:
- Verified complete-group fail-closed admission in
sound/soc/apple/macaudio.c:macaudio_tas5770_level()requiresti,tas5770lcompatible, exact 4-byteapple,speaker-config, and0 < level <= TAS2770_AMP_GAIN_MAX(0x14, shared fromsound/soc/codecs/tas2770.h), explicitly rejecting0so ASoC never interprets a zero maximum as unlimited.- Any missing, short, zero, out-of-range, or wrong-compatible amp makes
macaudio_amp_level_count()return0, skipping the speaker link inmacaudio_parse_of()(ma->has_speakers = 0) while leaving the jack card intact (macaudio_fixup_controls()returns early when!ma->has_speakers). - When speakers are admitted,
macaudio_limit_amp_levels()appliessnd_soc_limit_volume()to eachti,tas5770lcomponent, checksret == 1, and enforcescount == ma->tas_amp_countso no TAS amp can bypass limiting.
- Verified all
macaudio_platform_cfgdefinitions insound/soc/apple/macaudio.c: every positional initializer (j180,j274,j293,j313,j314,j316,j37x_j47x,j413,j415,j45x,j493,fallback) cleanly dropsamp_gainwithsafe_volpreserved; all other boards use designated initializers. - Verified DT binding
Documentation/devicetree/bindings/sound/ti,tas2770.yamlconstrainsapple,speaker-config(4-byteuint8-array) toti,tas5770land matches the merged bootloader provider (aurora-silicon/aura#542, merged atc0af820e31). - Verified CI & tests at
e3d44558:kunit(80/80apple-speaker-*),dt-checks, andpr-textpass; confirmedhost-testsrun46262667447failed exclusively onapple-scaler-recovery-tests(production.c:222incompletehdl/u16), unrelated to audio. - Verified silent SN012776 module regression rows on J473 (1 amp) and J413 (4 amps) (identical controls/TLV, 0 errors) and open tracking issue #3654 for the physical J313 TAS5770L row with a clean two-way revert path.
Evidence
sound/soc/apple/macaudio.c:2548-2653(macaudio_tas5770_level,macaudio_amp_level_count,macaudio_limit_amp_levels),:2852-2875(macaudio_parse_of),:4004-4014(macaudio_fixup_controls),:4405-4822(macaudio_platform_cfgtables).sound/soc/codecs/tas2770.h:28/tas2770.c:790: sharedTAS2770_AMP_GAIN_MAX(0x14).sound/soc/apple/macaudio-amp-level-test.handmacaudio-kunit.dtso: covers valid TAS rows (4,14), zero/high/short/missing rejections, and complete-group / wrong-compatible checks.- Bootloader dependency
aurora-silicon/aura#542verifiedMERGED(c0af820e3159ab1d53c687da292262b2da5af5ec). - Known-gap tracking issue
aurora-silicon/linux#3654verifiedOPEN.
|
code-owner ping <@422957901716652033> / @DjDeveloperr: merge train at |
|
Merge readiness at
Areas: Updated by pr-readiness on pushes, edits, reviews and comments, and on a schedule. Rules: merge policy · labels. |
|
Silent TAS5770L hardware rows on Mac mini (M1, J274 / T8103): both Tested at exact PR head
Notes:
|
DjDeveloperr
left a comment
There was a problem hiding this comment.
FINISH, then merge at e3d44558e610.
sound/soc/apple/macaudio.c:2642applies each DT limit to a named gain control, but all TAS5770L gain controls share the samesoc_mixer_control. With valid gains of 4 and 14, applying 14 second makes both controls report a maximum of 14. When speaker protection takes the lease,macaudio_spk_fix_amp_gains()writes that advertised maximum to each amp, so the amp rated for 4 can be set to 14. Give each TAS gain control its own mixer state before applying its limit. A two-control test should check that the maxima stay 4 and 14 and that the first control rejects 14.
Evidence
The TAS gain control comes from the static template at sound/soc/codecs/tas2770.c:790. snd_ctl_new1() copies the template’s private_value pointer at sound/core/control.c:315. Setting a limit changes the pointed-to platform_max at sound/soc/soc-ops.c:467. I checked those operations in memory with the two gains from the PR’s test fixture. Both controls reported 14. The lease uses that maximum at sound/soc/apple/macaudio.c:1772.
The DT parser rejects a missing or malformed row, zero, a gain above the codec range, or a different codec before registering the speaker backend. The change removes the board gain constants and adds no runtime switch or board check. The silent J274 runs confirmed that the jack stayed available with the row missing and that the one installed amp exposed its DT maximum of 20. J274 results
Signed-off-by: DjDeveloperr <hey@djdev.me>
|
Pushed |
DjDeveloperr
left a comment
There was a problem hiding this comment.
The two TAS gain controls now keep separate limits. The host test verified maxima of 4 and 14 and rejection of 14 on the first control. This resolves my earlier change request. I pushed the fix, so a separate maintainer approval is still needed. Silent J313 and J274 verification is pending.
|
Silent reference row, MacBook Neo J700 (MAX98360A), on repaired head
The probe's final report stopped on an incorrect U-Boot DT property path after the checks above. The U-Boot version comes from the restored saved boot, which supplied the loader handoff for this kernel-only trial. Both boots logged the same watchdog and multipathd shutdown errors. The candidate also logged a GNOME Global Shortcuts Provider exit during shutdown. This covers the MAX98360A reference path. The repaired-head TAS5770L per-amp check and SN012776 candidate boot remain open. |
Problem
macaudio uses a per-board analog gain cap on TAS5770L speakers. The protection lease fixes each amp at that cap, so it needs to come from the installed hardware's own configuration.
Change
Read the amp's operating gain from its device-tree row before registering the speaker backend. Apply the limit to each amp's codec control and keep the speaker backend closed if any row is unusable. Keep the existing sense-slot layout and the SN012776 fixed-ceiling check.
Depends on the bootloader handoff in aurora-silicon/aura#542. The booted loader needs to supply the rows before deploying this kernel to a TAS5770L Mac.
Tested
Arm64 macaudio and codec objects built with W=1. The binding passed dt-doc-validate and both commits passed checkpatch. All 73 macaudio KUnit cases passed in arm64 QEMU, including valid per-amp gain, a missing or malformed row, zero, out-of-range gain and a mismatched codec.
Hardware verification
The J274 owner verified both silent paths at published head
e3d44558e610. With the earlier Stage 2, the speaker backend stayed closed and jack and headset-mic controls remained visible. With Stage 2 that includes aura #542, the TAS gain control matched the DT limit and the kernel held the muted floor. This Debian boot still had legacy speakersafetyd, whose unlock request the kernel refused. The probe opened zero PCMs.The review found a shared mixer descriptor at that head. Repeat the silent TAS checks at the corrected head, including independent ALSA ceilings on a multi-amp J313. Run the silent MAX98360A and SN012776 reference rows in the same batch.
Risk: two-way · TAS5770L Macs (J274, J293, J313).
Compatibility and rollback