Skip to content
Closed
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
308 changes: 304 additions & 4 deletions device/cheetah/MODEM-PLAN.md

Large diffs are not rendered by default.

8 changes: 8 additions & 0 deletions packages/omamobile-device-cheetah/test/all
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,14 @@ pass "sitd waits for the CP; the modem stack is on by default through the target
|| fail "the device sitd policy is staged"
grep -q 'omamobile-sitd-policy' PKGBUILD || fail "the package provides its sitd policy capability"
pass "the device sitd policy is staged and provided"

# MODEM-PLAN section 7 (M6): the owner's modem-suspend-enable lifts
# omamobile-modem's sleep inhibitor only beside this marker, which only the
# Pixel 7 Pro ships; a plain data file, never a script.
runbook=$tmp/root/usr/lib/omamobile-modem/suspend-runbook
[[ -f $runbook && ! -x $runbook ]] || fail "the M6 runbook marker is staged as a plain file"
[[ $(grep -cv '^#' "$runbook") == 0 ]] || fail "the M6 runbook marker holds comments only"
pass "the M6 runbook marker is staged, so modem-suspend-enable can take effect on this phone"
# The USB gadget's MAC addresses stay the same across boots (omamobile-usb-mac),
# against a fake gadget: plain directories and files stand in for configfs.
for f in usr/bin/omamobile-usb-mac usr/lib/systemd/system/omamobile-usb-mac.service; do
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# SPDX-License-Identifier: MIT
# The Pixel 7 Pro's modem plan has a runbook for suspend with the modem up
# (device/cheetah/MODEM-PLAN.md section 7, M6). omamobile-modem lets the
# owner's /etc/omamobile/modem-suspend-enable lift its sleep inhibitor only
# beside this file, so the owner's file alone changes nothing on a phone
# whose device package doesn't ship it. Attended runs only, until M6 passes.
2 changes: 1 addition & 1 deletion packages/omamobile-device-cheetah/version
Original file line number Diff line number Diff line change
@@ -1 +1 @@
0.1.55
0.1.56
5 changes: 5 additions & 0 deletions packages/omamobile-modem-sit/etc/omamobile/modem-sit.conf
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,11 @@ roaming = yes
[control]
# Members of this group may use the calls/SMS socket (root always can).
group = wheel
# Tell the modem when the screen goes off and on, as stock's RIL does: with
# the screen off it stops its optional signal and dormancy reports, so it
# wakes the phone less (MODEM-PLAN 7.4, M6). Off until calls with the screen
# dark have been tested on this phone; yes turns it on, from sitd's next start.
#follow_screen = no

[audio]
# The AoC sound card for call audio: "none" connects calls without routing
Expand Down
1 change: 1 addition & 0 deletions packages/omamobile-modem-sit/install
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ install -Dm755 lib/omamobile-sit-config "$d/usr/lib/omamobile-sit/omamobile-sit-
install -Dm644 polkit/org.omamobile.modem-sit.policy "$d/usr/share/polkit-1/actions/org.omamobile.modem-sit.policy"
install -Dm644 share/apn-overrides.conf "$d/usr/share/omamobile/modem-sit/apn-overrides.conf"
for f in systemd/*.service; do install -Dm644 "$f" "$d/usr/lib/systemd/system/${f#systemd/}"; done
install -Dm755 systemd/system-sleep/omamobile-modem-sit "$d/usr/lib/systemd/system-sleep/omamobile-modem-sit"
install -Dm644 networkmanager/90-omamobile-rmnet.conf "$d/usr/lib/NetworkManager/conf.d/90-omamobile-rmnet.conf"
install -Dm644 etc/omamobile/modem-sit.conf "$d/etc/omamobile/modem-sit.conf"
install -Dm644 LICENSE "$d/usr/share/licenses/omamobile-modem-sit/LICENSE"
Expand Down
155 changes: 154 additions & 1 deletion packages/omamobile-modem-sit/lib/data_network.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,18 @@
dead bearer's route plus its DNS can outlive a short Wi-Fi outage, make
NetworkManager's connectivity check fail through it and keep the phone
offline with Wi-Fi up.

Around a system sleep the default route is taken away (SleepHold): at
logind's announcement NetworkManager takes Wi-Fi down, and a route through
the bearer would carry everything that had been talking over Wi-Fi, bring
the modem's link up and make the kernel refuse the sleep.
"""
import fcntl
import ipaddress
import json
import os
from pathlib import Path
import select
import signal
import struct
import subprocess
Expand Down Expand Up @@ -257,6 +263,130 @@ def wait_for_bearer(seconds):
time.sleep(1)


# How long after a sleep the cellular default route waits for Wi-Fi.
RETURN_GRACE = 10
SLEEP_MATCH = ("type='signal',interface='org.freedesktop.login1.Manager',"
"member='PrepareForSleep'")


def sleep_signal(line):
"""True or False for a logind PrepareForSleep line of busctl's JSON
monitor (a sleep is starting, or is over), None for anything else."""
try:
message = json.loads(line)
except ValueError:
return None
if not isinstance(message, dict) or message.get('member') != 'PrepareForSleep':
return None
data = (message.get('payload') or {}).get('data')
if isinstance(data, list) and len(data) == 1 and isinstance(data[0], bool):
return data[0]
return None


class SleepWatch:
"""logind's sleep announcements, read without blocking. Without busctl
nothing is heard, and the route simply stays as it was."""

def __init__(self):
self.buffer = b''
try:
self.process = subprocess.Popen(
['busctl', 'monitor', '--system', '--json=short', '--match', SLEEP_MATCH],
stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
os.set_blocking(self.process.stdout.fileno(), False)
except OSError:
self.process = None

def wait(self, seconds):
"""Sleep up to seconds; return the announcements heard, in order."""
if not self.process:
time.sleep(seconds)
return []
heard = []
ready, _, _ = select.select([self.process.stdout], [], [], seconds)
if ready:
chunk = os.read(self.process.stdout.fileno(), 65536)
if not chunk: # the monitor ended: go on without it
self.close()
return heard
self.buffer += chunk
*lines, self.buffer = self.buffer.split(b'\n')
for line in lines:
state = sleep_signal(line.decode(errors='replace'))
if state is not None:
heard.append(state)
return heard

def close(self):
if self.process:
self.process.terminate()
try:
self.process.wait(timeout=2)
except subprocess.TimeoutExpired:
self.process.kill()
self.process = None


class SleepHold:
"""The cellular default route around a system sleep.

When the system goes to sleep NetworkManager takes Wi-Fi down first, and
the bearer's default route is then the only one: whatever was talking
over Wi-Fi sends through the bearer in that moment, the modem's link
comes up, and the kernel refuses the sleep because of it. So the route
goes at logind's announcement. After the sleep it waits for something
else to lead out again, or for RETURN_GRACE without that: put back at
once, it carried a few seconds of traffic at every wake, and the answers
to that traffic ended the next sleeps early.
"""

def __init__(self, grace=RETURN_GRACE):
self.grace = grace
self.sleeping = False
self.held = False # the route is ours to bring back
self.back_at = None # when it returns if nothing else leads out

@property
def active(self):
"""True while the route's presence is this class's business."""
return self.sleeping or self.back_at is not None

def announced(self, routed):
"""A sleep is starting. True when the route has to go now."""
if self.sleeping:
return False
self.sleeping = True
# Still waiting to return after the last sleep counts as held.
self.held = routed or self.back_at is not None
self.back_at = None
return routed

def over(self, now, allowed=True):
"""The sleep is over; allowed is False when roaming forbids data."""
if not self.sleeping:
return
self.sleeping = False
if self.held and allowed:
self.back_at = now + self.grace
self.held = False

def returns(self, others, now):
"""True once: the route comes back now (others: another default
route exists)."""
if self.sleeping or self.back_at is None:
return False
if others or now >= self.back_at:
self.back_at = None
return True
return False

def cancel(self):
"""Roaming took the route away for good: nothing to bring back."""
self.held = False
self.back_at = None


def main():
os.umask(0o077)
lock = os.open(paths.RUN / 'data-network.lock', os.O_CREAT | os.O_RDWR, 0o600)
Expand All @@ -275,6 +405,7 @@ def stop(*_):
signal.signal(signal.SIGTERM, stop)
signal.signal(signal.SIGINT, stop)
resolver = None
sleeps = None
try:
dev = find_device(address, data[2], stopped=lambda: stopping)
addressed = True
Expand All @@ -286,6 +417,7 @@ def stop(*_):
last = None
seen = counters(json.loads(run('ip', '-j', '-s', 'link', 'show', 'dev', dev)))
check_at = time.monotonic() + 30
hold = SleepHold()

def watch():
nonlocal last, seen, check_at
Expand All @@ -297,6 +429,7 @@ def watch():
run('ip', 'route', 'del', 'default', 'dev', dev, 'metric', '700')
print('Roaming with data roaming off; the cellular default route is removed', flush=True)
resolver.update(False, dns)
hold.cancel()
last = None
return
# With Wi-Fi up but rated limited, the carrier's DNS would keep
Expand All @@ -306,6 +439,13 @@ def watch():
if cellular != last:
print('Default internet path', 'cellular' if cellular else 'Wi-Fi/other', flush=True)
last = cellular
if hold.active:
if hold.returns(bool(others), time.monotonic()):
if not routed:
run('ip', 'route', 'add', 'default', 'dev', dev, 'src', address, 'metric', '700')
print('The cellular default route is back', 'behind Wi-Fi' if others else 'as the only way out', flush=True)
last = None
return
if not routed and not others:
run('ip', 'route', 'add', 'default', 'dev', dev, 'src', address, 'metric', '700')
print('Nothing else leads out; the cellular default route is back', flush=True)
Expand All @@ -317,6 +457,16 @@ def watch():
now = counters(json.loads(run('ip', '-j', '-s', 'link', 'show', 'dev', dev)))
seen = now
check_at = time.monotonic() + 30
def announced(state):
if not state:
hold.over(time.monotonic(), not roaming_blocked())
return
routes = json.loads(run('ip', '-j', 'route', 'show', 'default'))
routed = any(r.get('dev') == dev and r.get('metric') == 700 for r in routes)
if hold.announced(routed):
run('ip', 'route', 'del', 'default', 'dev', dev, 'metric', '700')
print('Sleep announced; the cellular default route is away until it is over', flush=True)
sleeps = SleepWatch()
failing = None
while not stopping and cp.online() and RESPONSE.exists():
error = guarded(watch)
Expand All @@ -325,11 +475,14 @@ def watch():
elif failing and not error:
print('Network checks work again', flush=True)
failing = error
time.sleep(2 if error else .5)
for state in sleeps.wait(2 if error else .5):
guarded(lambda state=state: announced(state))
except InterruptedError:
# Stopped while probing: find_device has put the candidate back.
pass
finally:
if sleeps:
sleeps.close()
if resolver:
resolver.restore()
if dev:
Expand Down
2 changes: 1 addition & 1 deletion packages/omamobile-modem-sit/lib/paths.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@
# Extra modem-managed data profiles, one per line (data_call.parse_profile).
'profiles': {},
'data': {'route': 'yes', 'metric': '700', 'roaming': 'yes'},
'control': {'group': 'wheel'},
'control': {'group': 'wheel', 'follow_screen': 'no'},
'audio': {'card': 'none', 'mic_boost_db': '6', 'earpiece': 'yes'},
}

Expand Down
61 changes: 59 additions & 2 deletions packages/omamobile-modem-sit/lib/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
import struct
import subprocess
import time
from pathlib import Path

import cp
import paths
Expand All @@ -58,6 +59,8 @@
RATS = {0: '', 1: 'GPRS', 2: 'EDGE', 3: 'UMTS', 9: 'HSDPA', 10: 'HSUPA', 11: 'HSPA',
14: 'LTE', 15: 'HSPA+', 16: 'GSM', 20: 'LTE-CA', 21: 'NR', 22: 'NR'}
SOCKET = paths.RUN / 'socket'
# The panel's power, which the shell drives (bl_power 4 = off, 0 = on).
BACKLIGHT = Path(os.environ.get('OMAMOBILE_SIT_BACKLIGHT', '/sys/class/backlight'))
# GET_RADIO_POWER / IND_RADIO_STATE_CHANGED (MODEM-SIT-RESEARCH 3.1):
# INITIALIZED and STOP_NETWORK are off, START_NETWORK on, POWER_OFF is the
# state without a SIM (M4.1i), RESET is unavailable. GET_RADIO_POWER answers
Expand Down Expand Up @@ -219,6 +222,13 @@ def __init__(self, client, db, settings=None):
self.hangup_deadline = None
self.release_unconfirmed = False
self.screen_on = None
self.next_screen_check = 0
# [control] follow_screen: off by default until calls with the
# screen dark are tested (MODEM-PLAN 7.4).
try:
self.follow = self.settings['control'].getboolean('follow_screen', False)
except ValueError:
self.follow = False
self.indication_counts = {}
self.net = dict(reg='unknown', rat='', operator='', plmn='')
self.last_registration = None
Expand Down Expand Up @@ -642,12 +652,50 @@ def publish(self):
tmp.chmod(0o644)
tmp.replace(path)

def follow_screen(self, now=None):
"""Tell the modem when the panel goes off or on, as stock's RIL does:
with the screen off it sends the optional signal and dormancy reports
no more (calls, SMS and registration changes still come), so it wakes
the AP less. Off only when a backlight positively reads off; never
during a call (stock keeps the reports then, and screen-state refuses
it), and a failed request waits 30 s before the next try. Only with
[control] follow_screen = yes in modem-sit.conf."""
if not self.follow:
return
now = time.monotonic() if now is None else now
if now < self.next_screen_check:
return
self.next_screen_check = now + 2
states = []
for power in sorted(BACKLIGHT.glob('*/bl_power')):
try:
states.append(power.read_text().strip() != '0')
except OSError:
pass
if not states:
return
on = not any(states)
if on == self.screen_on or (not on and self.live()):
return
try:
self.dispatch(dict(action='screen-state', on=on))
print('Screen', 'on' if on else 'off', 'told to the modem', flush=True)
except (OSError, RuntimeError, ValueError) as e:
print('Screen state not sent:', e, flush=True)
self.next_screen_check = now + 30

def dispatch(self, request):
action = request.get('action')
if action == 'screen-state':
on = request.get('on')
if type(on) is not bool:
raise ValueError('Screen state must be boolean')
hold = request.get('hold', 0)
if type(hold) is not int or not 0 <= hold <= 60:
raise ValueError('Screen hold must be 0 to 60 s')
if hold and not self.follow:
# The sleep hook, on a phone that doesn't follow the screen.
return dict(screen_on=self.screen_on, following=False)
if not on and self.live():
raise RuntimeError('Call in progress')
if on != self.screen_on:
Expand All @@ -661,6 +709,10 @@ def dispatch(self, request):
# reporting. Cache only after both replies succeed.
self.client.request(0x0928, struct.pack('<I', 0xffffffff if on else 0), timeout=5)
self.screen_on = on
if hold:
# The sleep hook's "off" with the panel still lit: keep
# follow_screen from taking it back before the freeze.
self.next_screen_check = time.monotonic() + hold
return dict(screen_on=self.screen_on)
if action == 'radio':
# The rollback for a running registration short of a reboot:
Expand Down Expand Up @@ -942,15 +994,20 @@ def stop(*_):
notify('READY=1\nSTATUS=registered')
print('Calls and SMS service ready', flush=True)
# Set by a device whose modem sends signal reports only after it's
# told the screen is on (the Pixel 9a's drop-in), while nothing else
# sends the screen state yet. Never set on the 7 Pro.
# told the screen is on (the Pixel 9a's drop-in). Nothing else sends
# the screen state unless the owner sets [control] follow_screen =
# yes (off by default; MODEM-PLAN section 7, M6, on the 7 Pro only
# so far), which then follows the panel from here on. Never set on
# the 7 Pro.
if args.bringup and os.environ.get('OMAMOBILE_SIT_SCREEN_ON_AT_START') == '1' \
and service.screen_on is None:
service.dispatch(dict(action='screen-state', on=True))
next_cp_check = 0
while not stopping:
service.pump()
service.poll()
if args.bringup: # without it the service writes nothing to the modem
service.follow_screen()
if time.monotonic() >= next_cp_check:
if not cp.online():
raise RuntimeError('CP left ONLINE; the modem unit keeps its crash record')
Expand Down
Loading