Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 9 additions & 4 deletions device/cheetah/MODEM-CLIENT.md
Original file line number Diff line number Diff line change
Expand Up @@ -112,10 +112,15 @@ registration indication), unless `ims_required = yes`.
- **Outgoing SMS** carry a durable 32-hex request id; an interrupted or
uncertain send is marked `unknown`, never repeated automatically.
- **Calls**: a hangup whose release isn't confirmed within 12 s, or a call
left over from a previous run, stops the modem unit (CP off, then rfsd):
the only way to be sure the radio isn't still carrying a call. That is a
CP power-off (one UFS handler pass) and is the one place the RIL powers
the modem off.
left over from a previous run, turns the radio off (best effort, AT+CFUN=0)
and stops sitd with the call still recorded as its own, for an attended
reboot. The journal says "Call release not confirmed: <reason>", the radio
and CP states, and "attended reboot required". The RIL no longer stops the
modem unit or powers the CP off: an in-place power-off reset the 9a once,
and on the 7 Pro every power-off costs a UFS error-handler pass. The unit
has `Restart=no`, so a manual restart in the same boot finds the recorded
call, turns the radio off again and exits. This path has run only in the
simulator.
- **Storage**: received SMS in `/var/lib/omamobile-sit` (0700, files 0600):
numbers and text, never to be copied into the repository.

Expand Down
7 changes: 4 additions & 3 deletions device/cheetah/MODEM-PLAN.md
Original file line number Diff line number Diff line change
Expand Up @@ -1527,7 +1527,8 @@ tools/phone-ssh 'omamobile-sit hangup; sleep 2; omamobile-sit status;
# "AoC call routes restored". Then the human calls the phone: `omamobile-sit answer`, talk, hangup
# stop: no audio either way (record the journal: "voice PCM ... failed" means the AoC card; check that
# PipeWire does not hold PCM 4/11), distorted or loud audio (hang up at once), a release that is
# never confirmed (the RIL stops the modem unit by design after 12 s: one UFS pass; reboot after)
# never confirmed (after 12 s the RIL turns the radio off and exits: "Call release not confirmed",
# "attended reboot required"; reboot, which powers the CP off: one UFS pass)
# rollback: omamobile-sit hangup

# M4.6 at boot: superseded by "M4.6: the modem stack at boot" at the end of section 3 (one switch,
Expand Down Expand Up @@ -2638,8 +2639,8 @@ tools/phone-ssh 'omamobile-sit answer; sleep 10; omamobile-sit status | grep -E
# outgoing, to the human's other phone (international form); answer it there, hang up there after ~10 s:
tools/phone-ssh 'omamobile-sit dial <NUMBER>; sleep 30; omamobile-sit status | grep -E "^call"'
# pass: the other phone rings and connects (silent), then "terminated" after the remote hang-up
# stop: "Call release was not confirmed; modem stopped" (the RIL powered the CP off by design: one UFS
# pass; reboot before anything else); a CP crash; any sound from the phone's speakers (stop at once:
# stop: "Call release not confirmed" and "attended reboot required" (the RIL turned the radio off and
# exited, leaving the CP on; reboot before anything else, one UFS pass on the way down); a CP crash; any sound from the phone's speakers (stop at once:
# nothing should route audio: record `amixer -c <aoc card> cget name="TDM_0_RX Mixer EP5"`)
# rollback: omamobile-sit hangup
# Never dial an emergency number to test (refused anyway; TELEPHONY-APPS-PLAN 3.3)
Expand Down
7 changes: 4 additions & 3 deletions device/tegu/MODEM-PLAN.md
Original file line number Diff line number Diff line change
Expand Up @@ -1935,9 +1935,10 @@ tools/phone-ssh 'omamobile-sit sms send <NUMBER> "omamobile test"'

# SIM-10 calls: NOT in this test. No audio route exists on the 9a (table above). A signalling-only call
# (ring, answer, hang up, silence both ways, as cheetah's S10) is its own later step, after this runbook passes.
# Nobody calls the palmtop's number during the test: an incoming call that sitd can't release makes its
# safety stop target omamobile-modem.service, which is masked on the 9a, so it would only time out. If the
# journal says a call release wasn't confirmed ("call release not confirmed" or the stop timing out): don't
# Nobody calls the palmtop's number during the test: an incoming call that sitd can't release makes it
# turn the radio off and exit for an attended reboot (since #364; before it, its safety stop targeted
# omamobile-modem.service, masked on the 9a). If the journal says "Call release not confirmed" or
# "attended reboot required": don't
# stop anything by hand; "omamobile-sit radio off", record the journal lines (states and codes), and end
# the session with SIM-11's attended reboot.

Expand Down
29 changes: 4 additions & 25 deletions packages/omamobile-modem-sit/lib/cp.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,12 @@
# SPDX-License-Identifier: MIT
"""The CP (modem) state from CPIF, and the one way this stack powers it off.
"""Read the CP state without stopping or restarting the modem.
The modem stays on once it is up (device/cheetah/MODEM-PLAN.md M2.6: every
modem power-off costs one recovered UFS error-handler pass). The RIL powers
it off only when a call's release can't be confirmed: then stopping the
modem unit is the only way to be sure the radio isn't carrying a call. The
unit's stop powers the CP off before rfsd goes (omamobile-modem profile).
An in-place modem stop has reset tegu. Unconfirmed calls are handled by
service.py with best-effort radio-off and an attended-reboot requirement;
the CP and its NV server stay running until shutdown.
"""
import fcntl
import os
import subprocess
import time

from paths import BOOT

Expand All @@ -19,7 +15,6 @@
5: 'nv-rebuilding', 6: 'loader-done', 7: 'sim-attach', 8: 'sim-detach',
9: 'crash-watchdog'}
ONLINE = 4
MODEM_UNIT = 'omamobile-modem.service'


# One open file for every status request. On the Pixel 9a each open and
Expand Down Expand Up @@ -49,19 +44,3 @@ def state():

def online():
return state() == ONLINE


def stop_modem(reason):
"""Stop the modem unit (CP off, then rfsd) and wait for OFFLINE."""
print('Stopping the modem:', reason, flush=True)
if BOOT == 'none':
return
subprocess.run(['systemctl', 'stop', '--no-block', MODEM_UNIT],
stdin=subprocess.DEVNULL, capture_output=True, timeout=20)
deadline = time.monotonic() + 30
while time.monotonic() < deadline:
if state() == 0:
print('CP OFFLINE', flush=True)
return
time.sleep(.25)
raise RuntimeError('CP shutdown not confirmed; reboot the phone')
6 changes: 4 additions & 2 deletions packages/omamobile-modem-sit/lib/data_call.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,8 +219,10 @@ def setup_payload(cid, radio_technology, pdu_session, apn, *, ims=False, ip_type
# ApnSetting's supported types (vendor.radio.base
# ApnSetting::SetSupportedTypesBitmask, member +0x160; the 983-byte
# builder writes it at 0xf1). DEFAULT for the internet bearer, IMS for
# the IMS one. Until 0.3.6 this was sent as 0 (taken for an MTU), and
# the 9a's modem answered every internet setup with status 36.
# the IMS one. Until 0.3.6 this was sent as 0 (taken for an MTU). It
# wasn't the cause of the 9a's status 36: 0.3.7 sent the bitmap and
# still got 36, and 0.3.8's wait after the data permission fixed it
# (device/tegu MODEM-PLAN, "SIM test results").
# apn_types: the whole bitmask of the APN's data profile, as stock's
# builder copies it (ApnSetting +0x160 -> 0xf1); Verizon's IMS APN is
# ims|ia (0x140), which stock's IMS setup carries.
Expand Down
67 changes: 52 additions & 15 deletions packages/omamobile-modem-sit/lib/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,37 @@ def signal_percent(rsrp):
SUBSCRIBERS = 8


class UnconfirmedRelease(RuntimeError):
"""Fatal call ownership failure; never turn this into a socket reply."""


def unconfirmed_release(client, reason):
"""Stop serving an uncertain call without power-cycling the CP.

In-place modem stops have reset tegu. Radio-off is best effort: even
an accepted command does not establish that the call was released.
Keep call ownership and the modem/NV server for an attended reboot.
"""
print('Call release not confirmed:', reason, flush=True)
try:
radio(False)
print('Recovery radio-off command accepted', flush=True)
except (OSError, RuntimeError, ValueError) as error:
print('Recovery radio-off failed:', type(error).__name__, flush=True)
try:
payload = client.request(0x0801, timeout=5)
state = RADIO.get(struct.unpack('<I', payload)[0], 'unknown') if len(payload) == 4 else 'unexpected'
except (OSError, RuntimeError, ValueError) as error:
state = 'unavailable (' + type(error).__name__ + ')'
try:
modem = cp.STATES.get(cp.state(), 'unknown')
except OSError:
modem = 'unavailable'
print('Unconfirmed release recovery: radio', state, 'CP', modem,
'; leaving the modem running for an attended reboot', flush=True)
raise UnconfirmedRelease('Call release was not confirmed; stopping sitd; attended reboot required')


def sim_status(payload):
"""GET_SIM_STATUS without identifiers: the card state, and the USIM's
(else the first application's) state and PIN/PUK retries. AIDs and
Expand Down Expand Up @@ -182,6 +213,7 @@ def __init__(self, client, db, settings=None):
self.muted = False
self.pending = None
self.hangup_deadline = None
self.release_unconfirmed = False
self.screen_on = None
self.indication_counts = {}
self.net = dict(reg='unknown', rat='', operator='', plmn='')
Expand Down Expand Up @@ -462,8 +494,8 @@ def pump(self):
break
self.event(packet)
if self.hangup_deadline and time.monotonic() > self.hangup_deadline:
cp.stop_modem('a call release was not confirmed')
raise RuntimeError('Call release was not confirmed; modem stopped')
self.release_unconfirmed = True
unconfirmed_release(self.client, 'hangup deadline expired')

def send_sms(self, request):
key = request.get('request_id', '')
Expand Down Expand Up @@ -783,6 +815,9 @@ def serve_one(service, connection, clients):
return True
result = service.dispatch(request)
response = dict(ok=True, result=result)
except UnconfirmedRelease:
connection.close()
raise
except (ValueError, KeyError, TypeError, RuntimeError, OSError) as error:
# Errors from wire data must never expose raw values.
response = dict(ok=False, error=str(error) if isinstance(error, RuntimeError)
Expand Down Expand Up @@ -856,8 +891,7 @@ def stop(*_):
try:
marker = paths.RUN / 'active.json'
if marker.exists() and json.loads(marker.read_text()):
cp.stop_modem('a call from the previous service run was never released')
raise RuntimeError('Previous call ownership unresolved; modem stopped')
unconfirmed_release(client, 'a call from the previous service run was never released')
service = Service(client, database(paths.STATE / 'apps.db'), settings)
service.publish()
for sms in paths.INBOX.glob('*.sit'):
Expand Down Expand Up @@ -904,7 +938,7 @@ def stop(*_):
service.broadcast()
finally:
try:
if service and service.live():
if service and service.live() and not service.release_unconfirmed:
for call in service.live():
if call['modem_id'] is not None:
try:
Expand All @@ -917,17 +951,20 @@ def stop(*_):
if packet:
service.event(packet)
if service.live():
cp.stop_modem('a call release was not confirmed at service stop')
if service:
service.audio_stop()
service.release_unconfirmed = True
unconfirmed_release(client, 'a call release was not confirmed at service stop')
finally:
if service:
for connection in list(service.subscribers):
service.drop(connection)
client.close()
server.close()
SOCKET.unlink(missing_ok=True)
(paths.RUN / 'state.json').unlink(missing_ok=True)
try:
if service:
service.audio_stop()
finally:
if service:
for connection in list(service.subscribers):
service.drop(connection)
client.close()
server.close()
SOCKET.unlink(missing_ok=True)
(paths.RUN / 'state.json').unlink(missing_ok=True)


if __name__ == '__main__':
Expand Down
40 changes: 35 additions & 5 deletions packages/omamobile-modem-sit/test/test_service.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
# SPDX-License-Identifier: MIT
import env # noqa: F401 (paths and sys.path first)
import json
import os
from pathlib import Path
import struct
import socket
import tempfile
import unittest
from unittest.mock import Mock, MagicMock, patch
Expand Down Expand Up @@ -62,6 +64,29 @@ def test_restart_does_not_retry_pending_sms(self):
self.db.execute('INSERT INTO outgoing VALUES (?,?,?,?,?)',('a'*32,'digest','sending','',0)); self.db.commit()
other=app_service.database(self.root/'db')
self.assertEqual(other.execute('SELECT state FROM outgoing').fetchone()[0],'unknown'); other.close()

def test_failed_radio_off_still_requires_reboot_without_claiming_release(self):
self.client.request.side_effect = TimeoutError()
with patch.object(app_service, 'radio', side_effect=OSError()), \
patch.object(app_service.cp, 'state', side_effect=OSError()), \
patch('builtins.print') as printed:
with self.assertRaisesRegex(RuntimeError, 'attended reboot required'):
app_service.unconfirmed_release(self.client, 'hangup deadline expired')
log = ' '.join(' '.join(map(str, call.args)) for call in printed.call_args_list)
self.assertIn('hangup deadline expired', log)
self.assertIn('radio-off failed: OSError', log)
self.assertIn('radio unavailable (TimeoutError) CP unavailable', log)
self.assertIn('leaving the modem running', log)

def test_unconfirmed_release_during_socket_request_is_fatal(self):
mine, theirs = socket.socketpair()
self.addCleanup(mine.close)
self.addCleanup(theirs.close)
theirs.sendall(b'{"action":"status"}\n')
self.service.dispatch = Mock(side_effect=app_service.UnconfirmedRelease('attended reboot required'))
with self.assertRaises(app_service.UnconfirmedRelease):
app_service.serve_one(self.service, mine, {os.getuid()})
self.assertEqual(mine.fileno(), -1)
def test_ring_does_not_autoanswer_and_release_restores_audio(self):
n=b'+12025550123'; body=struct.pack('<HBH',1,7,len(n))+n
packet=struct.pack('<BBHHH',2,0,0x0d01,8+len(body),0)+body
Expand Down Expand Up @@ -193,14 +218,19 @@ def test_network_state_indication_brings_the_poll_forward(self):
self.service.event(struct.pack('<BBHH', 2, 0, 0x070e, 8))
self.assertLessEqual(self.service.next_poll, time.monotonic() + 5)

def test_unconfirmed_release_stops_the_modem(self):
def test_unconfirmed_release_turns_radio_off_and_keeps_call_ownership(self):
call=self.service.new_call('+12025550123','outgoing','active',7)
with patch.object(app_service.cp,'stop_modem') as stop:
self.client.request.return_value = struct.pack('<I', 1)
with patch.object(app_service, 'radio') as radio, \
patch.object(app_service.cp, 'state', return_value=app_service.cp.ONLINE):
self.service.dispatch(dict(action='hangup',id=call['id']))
stop.assert_not_called()
radio.assert_not_called()
self.service.hangup_deadline=0.001
with self.assertRaises(RuntimeError): self.service.pump()
stop.assert_called_once()
with self.assertRaises(app_service.UnconfirmedRelease): self.service.pump()
radio.assert_called_once_with(False)
self.assertTrue(self.service.release_unconfirmed)
self.assertEqual(self.service.live(), [call])
self.assertTrue(json.loads((self.root/'active.json').read_text()))


class RefusedAudioTests(unittest.TestCase):
Expand Down
50 changes: 50 additions & 0 deletions packages/omamobile-modem-sit/test/test_sim.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,56 @@ def control(self, command):
with socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) as sock:
sock.sendto(command.encode(), str(self.dir / 'control'))

def active_call(self):
call = self.cli('dial', '+12025550199').strip()
deadline = time.monotonic() + 5
while time.monotonic() < deadline:
calls = json.loads(self.cli('status', '--json'))['calls']
if calls and calls[0]['state'] == 'active':
return call
time.sleep(.1)
self.fail('call did not become active')

def assert_release_recovery(self, reason, hangups):
self.assertNotEqual(self.daemon.wait(25), 0)
# Radio-off and sitd exit leave the simulated CP and call ownership
# intact. A subsequent service start must not silently reuse it.
self.assertIsNone(self.procs[0].poll())
self.assertTrue(json.loads((self.dir / 'run' / 'active.json').read_text()))
self.assertFalse((self.dir / 'run' / 'socket').exists())
self.assertFalse((self.dir / 'run' / 'state.json').exists())
entries = self.transcript_entries()
self.assertFalse([e for e in entries if 'violation' in e])
self.assertEqual([e['cmd'] for e in entries if e.get('type') == 'at'][-1], 'AT+CFUN=0')
ids = [e['id'] for e in entries if e.get('type') == 'req']
self.assertEqual(ids.count(0x0d03), hangups)
self.assertEqual(ids[-1], 0x0801)
log = (self.dir / 'daemon.log').read_text()
self.assertIn(reason, log)
self.assertIn('radio off CP online', log)
self.assertIn('attended reboot required', log)
self.assertNotIn('Stopping the modem', log)
self.assertNotIn('2025550', log)

def test_unconfirmed_hangup_turns_radio_off_and_exits_without_stopping_modem(self):
self.start('--unconfirmed-hangup')
self.wait_ready()
self.active_call()
self.cli('hangup')
self.assert_release_recovery('hangup deadline expired', 1)

def test_unconfirmed_release_at_service_stop_leaves_modem_for_reboot(self):
self.start('--unconfirmed-hangup')
self.wait_ready()
self.active_call()
self.daemon.send_signal(signal.SIGTERM)
self.assert_release_recovery('a call release was not confirmed at service stop', 1)

def test_unresolved_previous_call_turns_radio_off_before_exiting(self):
(self.dir / 'run' / 'active.json').write_text('[{}]')
self.start(bringup=False)
self.assert_release_recovery('a call from the previous service run was never released', 0)

def subscribe(self):
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.settimeout(10)
Expand Down
2 changes: 1 addition & 1 deletion packages/omamobile-modem-sit/version
Original file line number Diff line number Diff line change
@@ -1 +1 @@
0.3.27
0.3.28
9 changes: 7 additions & 2 deletions tools/sit-sim
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,12 @@ fictional 555-01xx ones, addresses are from the documentation ranges.
tools/sit-sim --ipc PATH --router PATH [--transcript FILE] [--search-polls N]
[--incoming-sms] [--no-sim] [--reject-setup CAUSE]
[--no-ims-registration] [--control PATH]
[--no-ims-registration] [--unconfirmed-hangup] [--control PATH]
--no-ims-registration accepts ADD_PDN_INFO but never registers IMS (a
carrier whose IMS values differ). --control PATH is a datagram socket for tests: "ring" (an incoming IMS call),
carrier whose IMS values differ). --unconfirmed-hangup acknowledges hangup
requests but leaves the call active and never sends a release indication.
--control PATH is a datagram socket for tests: "ring" (an incoming IMS call),
"remote-hangup" (the far end ends the current call), "sms" (one text
message), "wap-push" (one MMS notification: an 8-bit SMS to port 2948).
Expand Down Expand Up @@ -268,6 +270,8 @@ class Sim:
self.after(0.2, lambda: self.call_status(call_id, 0))

def r_0d03(self, mid, token, p): # AIMS_HANGUP
if self.a.unconfirmed_hangup:
return self.respond(mid, token)
self.calls.pop(p[0], None)
self.respond(mid, token)
self.after(0.05, lambda: self.call_status(p[0], 6, 16))
Expand Down Expand Up @@ -340,6 +344,7 @@ def main():
p.add_argument('--no-sim', action='store_true')
p.add_argument('--reject-setup', type=int, default=0)
p.add_argument('--no-ims-registration', action='store_true')
p.add_argument('--unconfirmed-hangup', action='store_true')
p.add_argument('--control')
p.add_argument('-v', '--verbose', action='store_true')
a = p.parse_args()
Expand Down