feat(cellular): add datapath validation and reject unimplemented BAM transport
Offline project checks / check (push) Canceled after 0s

This commit is contained in:
shenlei
2026-11-12 17:44:36 +09:00
parent fbd049a1da
commit 7462e85088
12 changed files with 866 additions and 33 deletions
+10 -2
View File
@@ -75,6 +75,8 @@ def main():
log("3. Testing SSH login to server@172.16.42.1...")
code, out, err = run_ssh("uname -a; uptime")
log(f"SSH output:\n{out.strip()}\n{err.strip()}")
if code:
return 1
# 4. Check modules and IPA interface
log("4. Checking loaded modules and rmnet_ipa0...")
@@ -93,8 +95,11 @@ def main():
# 7. Bring up cellular data
log("7. Activating cellular data connection...")
code, out, err = run_ssh("sudo platina-cellular --up 2>&1 || sudo nmcli connection up platina-cellular 2>&1 || true")
code, out, err = run_ssh("sudo platina-cellular --up 2>&1")
log(f"Cellular activate output:\n{out.strip()}")
if code:
log("FAILURE: Cellular activation failed; no data test passed.")
return 1
# 8. Check IP and route
log("8. Checking IP address and routes...")
@@ -103,8 +108,11 @@ def main():
# 9. Test ping over cellular
log("9. Testing connectivity over cellular network...")
code, out, err = run_ssh("ping -I rmnet_ipa0 -c 4 1.1.1.1 2>&1 || ping -c 4 1.1.1.1 2>&1")
code, out, err = run_ssh("ping -I rmnet_ipa0 -c 4 -W 5 1.1.1.1 2>&1")
log(f"Ping result:\n{out.strip()}")
if code:
log("FAILURE: No verified IP traffic over rmnet_ipa0.")
return 1
# 10. Check dmesg for IPA messages
log("10. Checking kernel log for IPA runtime messages...")
+1
View File
@@ -27,6 +27,7 @@ HELPERS = {
'scripts/phone-usb-power.py': 'usr/local/sbin/platina-usb-power',
'scripts/phone-usb-power-dispatcher.sh': 'etc/NetworkManager/dispatcher.d/90-platina-usb-power',
'scripts/phone-cellular-setup.py': 'usr/local/sbin/platina-cellular',
'scripts/phone-cellular-rpmsg.py': 'usr/local/sbin/platina-cellular-rpmsg',
'scripts/phone-mesh.py': 'usr/local/sbin/platina-mesh',
'scripts/phone-mesh.openrc': 'etc/init.d/easytier',
'scripts/phone-mesh-dispatcher.sh': 'etc/NetworkManager/dispatcher.d/95-platina-mesh',
+439
View File
@@ -0,0 +1,439 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-2.0-only
"""Probe modem AT support or run experimental PPP over an unused GLINK channel.
Default mode sends AT only. --query reads registration and PDP capabilities.
--connect requires an explicit APN and never installs a default route or DNS.
An AT OK or CONNECT response alone does not prove cellular IP connectivity.
"""
import argparse
from concurrent.futures import ThreadPoolExecutor
from contextlib import contextmanager, nullcontext
import errno
import fcntl
import ipaddress
import json
import os
from pathlib import Path
import pty
import re
import select
import shutil
import signal
import socket
import struct
import subprocess
import time
import tty
@contextmanager
def exclusive_session(path='/run/lock/platina-cellular-rpmsg.lock'):
fd = os.open(path, os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o600)
try:
try:
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
raise RuntimeError('Another RPMsg cellular session is active') from None
yield
finally:
os.close(fd)
@contextmanager
def open_channel(channel='DS', timeout=5, sys_path='/sys', dev_path='/dev'):
if not re.fullmatch(r'DS|DATA(?:1|2|3|4|11)', channel):
raise ValueError('Select DS, DATA1, DATA2, DATA3, DATA4, or DATA11')
root = Path(sys_path)
matches = list((root / 'bus/rpmsg/devices').glob(
f'4080000.remoteproc:glink-edge.{channel}.*'))
if len(matches) != 1:
raise RuntimeError(f'Expected one modem {channel} channel, found {len(matches)}')
device = matches[0]
if (device / 'driver').exists():
raise RuntimeError(f'{channel} is already bound; refusing to take it over')
driver = root / 'bus/rpmsg/drivers/rpmsg_chrdev'
override = device / 'driver_override'
previous = override.read_text().strip()
if previous == '(null)':
previous = ''
fd = None
bound = False
try:
override.write_text('rpmsg_chrdev\n')
(driver / 'bind').write_text(device.name + '\n')
bound = True
deadline = time.monotonic() + timeout
while True:
endpoints = [p for p in (device / 'rpmsg').glob('rpmsg*')
if re.fullmatch(r'rpmsg\d+', p.name)]
if len(endpoints) == 1:
node = Path(dev_path) / endpoints[0].name
if node.exists():
break
if time.monotonic() >= deadline:
raise TimeoutError('RPMsg endpoint device did not appear')
time.sleep(0.05)
fd = os.open(node, os.O_RDWR | os.O_NONBLOCK)
yield fd
finally:
if fd is not None:
os.close(fd)
try:
if bound and (device / 'driver').exists() and (device / 'driver').resolve() == driver.resolve():
try:
(driver / 'unbind').write_text(device.name + '\n')
except OSError as exc:
if exc.errno not in (errno.ENOENT, errno.ENODEV):
raise
finally:
# GLINK closes and re-announces the service during unbind, which
# can remove the old sysfs device (and its override) immediately.
if override.exists():
try:
override.write_text(previous + '\n')
except OSError as exc:
if exc.errno not in (errno.ENOENT, errno.ENODEV):
raise
def send_message(fd, data):
# A blocking GLINK send requests a remote RX intent. trysend alone
# cannot make progress on channels which advertise intents on demand.
# GLINK bounds its intent request wait in the kernel (currently 10 s).
os.set_blocking(fd, True)
try:
if os.write(fd, data) != len(data):
raise RuntimeError('Incomplete RPMsg message write')
finally:
os.set_blocking(fd, False)
AT_RESULT = re.compile(rb'(?:^|[\r\n])(OK|ERROR|CONNECT(?: [^\r\n]*)?|'
rb'NO CARRIER|BUSY|NO DIALTONE|\+CME ERROR:[^\r\n]*)[\r\n]')
def at_command(fd, command, timeout=5):
if '\r' in command or '\n' in command or not command.startswith('AT'):
raise ValueError('Expected one AT command')
send_message(fd, command.encode('ascii') + b'\r')
deadline = time.monotonic() + timeout
response = bytearray()
while time.monotonic() < deadline and len(response) < 65536:
if not select.select([fd], [], [], max(0, deadline - time.monotonic()))[0]:
break
try:
data = os.read(fd, 65536)
except BlockingIOError:
continue
if not data:
raise RuntimeError('RPMsg channel closed')
response.extend(data)
match = AT_RESULT.search(response)
if match:
return {'command': command, 'result': match[1].decode('ascii'),
'response': response[:match.end()].decode('ascii', errors='replace'),
'trailing': bytes(response[match.end():])}
return {'command': command, 'result': 'TIMEOUT',
'response': response.decode('ascii', errors='replace'), 'trailing': b''}
def query(fd, timeout=5):
results = []
for command in ('AT', 'AT+CFUN?', 'AT+CPIN?', 'AT+CSQ', 'AT+COPS?',
'AT+CEREG?', 'AT+CGREG?', 'AT+CGATT?', 'AT+CGDCONT?',
'AT+CGDATA=?', 'AT+CEER'):
result = at_command(fd, command, timeout)
result.pop('trailing')
results.append(result)
if result['result'] == 'TIMEOUT':
break
return results
def ppp_command(terminal, interface='ppp0'):
if not re.fullmatch(r'ppp\d+', interface):
raise ValueError('PPP interface must be ppp followed by a number')
return ['pppd', terminal, '115200', 'nodetach', 'local', 'nocrtscts',
'noauth', 'noipdefault', 'nodefaultroute', 'noipv6', 'noccp',
'ipcp-accept-local', 'ipcp-accept-remote', 'ifname', interface,
'lcp-echo-interval', '10', 'lcp-echo-failure', '3', 'debug']
def interface_ipv4(interface):
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
try:
data = fcntl.ioctl(sock.fileno(), 0x8915, struct.pack('256s', interface.encode()))
address = socket.inet_ntoa(data[20:24])
return address if address != '0.0.0.0' else None
except OSError:
return None
def probe_dns(interface, target):
"""Query a public resolver over a socket explicitly bound to the PPP device."""
transaction = os.urandom(2)
request = transaction + struct.pack('!HHHHH', 0x0100, 1, 0, 0, 0)
request += b'\x07example\x03com\x00' + struct.pack('!HH', 1, 1)
errors = []
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BINDTODEVICE, interface.encode() + b'\0')
sock.settimeout(3)
sock.connect((target, 53))
for _ in range(3):
try:
sock.send(request)
response = sock.recv(4096)
if len(response) < 12 or response[:2] != transaction:
errors.append('Invalid DNS transaction')
continue
_, flags, questions, answers, _, _ = struct.unpack('!6H', response[:12])
if flags & 0x8000 and flags & 0x000f == 0 and questions == 1 and answers:
return {'kind': 'dns', 'interface': interface, 'target': target,
'exit_code': 0, 'response_bytes': len(response), 'answers': answers}
errors.append('DNS response without a successful answer')
except OSError as exc:
errors.append(str(exc))
return {'kind': 'dns', 'interface': interface, 'target': target,
'exit_code': 1, 'errors': errors}
def wait_registration(fd, timeout=60):
deadline = time.monotonic() + timeout
last_response = None
while True:
result = at_command(fd, 'AT+CEREG?', min(5, max(0.1, deadline - time.monotonic())))
result.pop('trailing')
if result['response'] != last_response:
print(json.dumps(result), flush=True)
last_response = result['response']
if re.search(r'\+CEREG:\s*\d+,\s*[15](?:\s*[,\r\n]|$)', result['response']):
return
if time.monotonic() >= deadline:
raise TimeoutError('Modem did not register for LTE packet service')
time.sleep(min(2, max(0, deadline - time.monotonic())))
@contextmanager
def data_session():
"""Temporarily own modem control, restoring the manager's initial state."""
subprocess.run(['platina-cellular', '--battery-check'], check=True)
manager_running = subprocess.run(['rc-service', 'modemmanager', 'status'],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL).returncode == 0
if manager_running:
subprocess.run(['rc-service', 'modemmanager', 'stop'], check=True)
try:
subprocess.run(['qmicli', '-d', 'qrtr://0', '--dms-set-operating-mode=online'],
check=True)
yield
finally:
if manager_running:
subprocess.run(['rc-service', 'modemmanager', 'start'], check=True)
def connect(fd, apn, interface='ppp0', duration=120, timeout=30, dial_method='atd',
registration_timeout=180, verify_target=None, verify_kind='ping'):
if not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9.-]{0,99}', apn):
raise ValueError('Invalid APN')
ppp_command('/dev/pts/0', interface) # validate before changing modem settings
if (Path('/sys/class/net') / interface).exists():
raise RuntimeError(f'{interface} already exists; refusing to take over a link')
if verify_target is not None:
address = ipaddress.IPv4Address(verify_target)
if not address.is_global:
raise ValueError('Verification requires a public IPv4 address')
verify_target = str(address)
if not shutil.which('pppd'):
raise RuntimeError('Install ppp-daemon first; pppd was not found')
subprocess.run(['platina-cellular', '--battery-check'], check=True)
for module in ('ppp_generic', 'ppp_async'):
subprocess.run(['modprobe', module], check=True)
# Keep the AT endpoint open while RF registers, before requesting a call.
for command in ('AT', 'ATE0', 'AT+CMEE=2'):
result = at_command(fd, command, timeout)
result.pop('trailing')
print(json.dumps(result), flush=True)
if result['result'] != 'OK':
raise RuntimeError(f'{command} returned {result["result"]}')
wait_registration(fd, registration_timeout)
dial = {'cgdata': 'AT+CGDATA="PPP",1', 'atd': 'ATD*99#'}[dial_method]
for command in (f'AT+CGDCONT=1,"IP","{apn}"', dial):
result = at_command(fd, command, timeout)
trailing = result.pop('trailing')
print(json.dumps(result), flush=True)
expected = 'CONNECT' if command == dial else 'OK'
if not result['result'].startswith(expected):
if command == dial:
error = at_command(fd, 'AT+CEER', 5)
error.pop('trailing')
print(json.dumps(error), flush=True)
raise RuntimeError(f'{command} returned {result["result"]}')
master, slave = pty.openpty()
proc = None
ping = None
dns_pool = None
dns_future = None
route = None
local_ip = None
verification = None
tx_bytes = rx_bytes = 0
try:
tty.setraw(slave)
os.set_blocking(master, False)
command = ppp_command(os.ttyname(slave), interface)
proc = subprocess.Popen(command)
to_pty = bytearray(trailing)
deadline = time.monotonic() + duration if duration else float('inf')
while proc.poll() is None and time.monotonic() < deadline:
if not local_ip:
local_ip = interface_ipv4(interface)
if verify_target and local_ip and ping is None and dns_future is None:
# Add, never replace, an exact host route and remove it below.
candidate = [f'{verify_target}/32', 'dev', interface, 'metric', '42760']
subprocess.run(['ip', 'route', 'add'] + candidate, check=True)
route = candidate
if verify_kind == 'dns':
dns_pool = ThreadPoolExecutor(max_workers=1)
dns_future = dns_pool.submit(probe_dns, interface, verify_target)
else:
ping = subprocess.Popen(['ping', '-n', '-I', interface, '-c', '4',
'-W', '3', verify_target], stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, text=True)
if dns_future is not None and dns_future.done():
verification = dns_future.result()
break
if ping is not None and ping.poll() is not None:
output, _ = ping.communicate()
verification = {'kind': 'ping', 'target': verify_target, 'exit_code': ping.returncode,
'output': output, 'interface': interface}
break
readable, writable, _ = select.select(
[fd, master], [master] if to_pty else [], [], 0.2)
if master in writable:
try:
count = os.write(master, to_pty)
del to_pty[:count]
except BlockingIOError:
pass
if fd in readable:
try:
data = os.read(fd, 65536)
except BlockingIOError:
data = None
if data == b'':
raise RuntimeError('Modem closed PPP channel')
if data:
to_pty.extend(data)
rx_bytes += len(data)
if len(to_pty) > 1024 * 1024:
raise RuntimeError('PPP receive queue exceeded 1 MiB')
if master in readable:
try:
data = os.read(master, 1024)
except BlockingIOError:
continue
except OSError as exc:
if exc.errno == errno.EIO:
break
raise
if data:
send_message(fd, data)
tx_bytes += len(data)
return {'interface': interface, 'local_ip': local_ip,
'bridge_tx_bytes': tx_bytes,
'bridge_rx_bytes': rx_bytes, 'pppd_exit': proc.poll(),
'verification': verification,
'ip_connectivity': bool(verification and verification['exit_code'] == 0)}
finally:
if ping is not None and ping.poll() is None:
ping.terminate()
try:
ping.wait(timeout=5)
except subprocess.TimeoutExpired:
ping.kill()
ping.wait()
if route is not None:
subprocess.run(['ip', 'route', 'del'] + route, check=False)
if dns_pool is not None:
dns_pool.shutdown(wait=True, cancel_futures=True)
if proc is not None and proc.poll() is None:
proc.terminate()
try:
proc.wait(timeout=5)
except subprocess.TimeoutExpired:
proc.kill()
proc.wait()
os.close(master)
os.close(slave)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--channel', default='DS')
parser.add_argument('--timeout', type=float, default=5)
modes = parser.add_mutually_exclusive_group()
modes.add_argument('--query', action='store_true')
modes.add_argument('--connect', action='store_true')
parser.add_argument('--apn', help='Required for --connect')
parser.add_argument('--interface', default='ppp0')
parser.add_argument('--dial-method', choices=('cgdata', 'atd'), default='atd')
parser.add_argument('--registration-timeout', type=float, default=180)
parser.add_argument('--glink-signals', type=int, choices=(0, 1),
help='Experimental GLINK signal value: 1 sets DTR/RTS, 0 clears them')
parser.add_argument('--verify-target', help='Temporarily route and probe this public IPv4 via PPP only')
parser.add_argument('--verify-kind', choices=('ping', 'dns'), default='ping')
parser.add_argument('--duration', type=float, default=120,
help='PPP run time in seconds; 0 runs until interrupted')
args = parser.parse_args()
if not 0 < args.timeout <= 30:
parser.error('--timeout must be between 0 and 30 seconds')
if args.connect and not args.apn:
parser.error('--connect requires --apn')
if args.duration < 0 or not args.duration < float('inf'):
parser.error('--duration must be finite and nonnegative')
if not 0 < args.registration_timeout <= 300:
parser.error('--registration-timeout must be between 0 and 300 seconds')
signal.signal(signal.SIGTERM, interrupted)
try:
with exclusive_session(), data_session() if args.connect else nullcontext():
with open_channel(args.channel, args.timeout) as fd:
signals = args.glink_signals
if args.connect and signals is None:
signals = 1
if signals is not None:
# _IOR(0xb5, 6, int); rpmsg_char consumes the scalar argument.
fcntl.ioctl(fd, 0x8004B506, signals)
if args.connect:
result = connect(fd, args.apn, args.interface, args.duration,
dial_method=args.dial_method,
registration_timeout=args.registration_timeout,
verify_target=args.verify_target,
verify_kind=args.verify_kind)
elif args.query:
result = query(fd, args.timeout)
else:
result = at_command(fd, 'AT', args.timeout)
result.pop('trailing')
print(json.dumps(result, indent=2))
if args.connect:
# A bridge's byte counts are not an Internet connectivity test.
if args.verify_target:
return 0 if result['ip_connectivity'] else 1
return 0 if result['local_ip'] and result['pppd_exit'] in (None, 0) else 1
if args.query:
return 0 if result and result[0]['result'] == 'OK' else 1
return 0 if result['result'] == 'OK' else 1
except (OSError, RuntimeError, ValueError, subprocess.SubprocessError) as exc:
print(json.dumps({'channel': args.channel, 'error': str(exc)}))
return 1
except KeyboardInterrupt:
return 130
def interrupted(signum, frame):
raise KeyboardInterrupt
if __name__ == '__main__':
raise SystemExit(main())
+53 -24
View File
@@ -101,27 +101,52 @@ def parse_mmcli_modem_info(raw_text):
return info
def cellular_datapath_status(sys_path='/sys'):
"""Inspect transport backing; a driver binding or interface name is insufficient.
The current IPA v2.6 shim has no BAM TX/RX implementation. Reject it even
when it exposes rmnet_ipa0. A future real backend must explicitly expose
modem/datapath_ready=1 before this integration permits activation.
"""
root = Path(sys_path)
rows = []
def read(path):
try:
return path.read_text().strip()
except OSError:
return ''
def transport(iface, seen):
resolved = iface.resolve()
if resolved in seen:
return False, 'cyclic lower-interface relationship'
seen = seen | {resolved}
for lower in sorted(iface.glob('lower_*')):
ready, reason = transport(lower, seen)
if ready:
return ready, reason
device = iface / 'device'
if not (device / 'driver').exists():
return False, 'no bound hardware transport'
version = read(device / 'ipa_version')
compatible = read(device / 'of_node/compatible').split('\0')
legacy = (version.startswith('2.') or
any(value in ('qcom,sdm660-ipa', 'qcom,ipa-v2.6') for value in compatible))
if legacy and read(device / 'modem/datapath_ready') != '1':
return False, 'IPA v2.6 shim: BAM TX/RX not implemented'
return True, 'bound hardware transport (IP connectivity unverified)'
for iface in sorted((root / 'class/net').glob('*')):
if iface.name.startswith(('rmnet', 'ipa', 'wwan')):
ready, reason = transport(iface, set())
rows.append({'interface': iface.name, 'ready': ready, 'reason': reason})
return {'ready': any(row['ready'] for row in rows), 'interfaces': rows}
def has_cellular_datapath(sys_path='/sys'):
"""Check if kernel has an active hardware cellular data path (bound IPA device or rmnet/wwan network interface)."""
p = Path(sys_path)
net_dir = p / 'class/net'
if net_dir.is_dir():
try:
for iface in net_dir.iterdir():
if iface.name.startswith(('rmnet', 'ipa', 'wwan0')):
return True
except OSError:
pass
ipa_driver = p / 'bus/platform/drivers/ipa'
if ipa_driver.is_dir():
try:
ignored = {'bind', 'unbind', 'uevent', 'module'}
for item in ipa_driver.iterdir():
if item.name not in ignored:
return True
except OSError:
pass
return False
"""Return whether a hardware transport is available for NM activation."""
return cellular_datapath_status(sys_path)['ready']
def check_battery_gate(min_capacity=15, min_voltage_uv=3700000, sys_path='/sys'):
@@ -359,7 +384,7 @@ def configure_cellular(apn=None, ifname='*', executor=subprocess.run):
def toggle_cellular(activate=True, executor=subprocess.run, datapath_checker=has_cellular_datapath):
"""Activate or deactivate cellular data connection."""
if activate and not datapath_checker():
raise RuntimeError("No hardware IPA or rmnet cellular data path in kernel; activation skipped to protect modem stability.")
raise RuntimeError("No usable cellular hardware transport; an IPA v2.6 shim or interface name alone cannot carry data.")
action = 'up' if activate else 'down'
cmd = ['nmcli', 'connection', action, CONNECTION_NAME]
return executor(cmd, check=True)
@@ -586,8 +611,10 @@ def main():
if args.status:
result = query_modem_info()
datapath = cellular_datapath_status()
if args.json:
result['has_datapath'] = has_cellular_datapath()
result['has_datapath'] = datapath['ready']
result['datapath'] = datapath
print(json.dumps(result, indent=2))
else:
if result.get('status') == 'ok':
@@ -606,8 +633,10 @@ def main():
print(f"Signal Quality: {modem.get('signal_percent')}%")
if modem.get('access_tech'):
print(f"Access Tech: {modem.get('access_tech')}")
if not has_cellular_datapath():
print("Data Path: Disabled (IPA hardware datapath not present in kernel)")
if not datapath['ready']:
print("Data Path: Unavailable (no usable hardware transport)")
for row in datapath['interfaces']:
print(f" {row['interface']}: {row['reason']}")
else:
print(f"Cellular Status: {result.get('message')}")
return 0
+1 -1
View File
@@ -103,7 +103,7 @@ def main():
return 1
log("SUCCESS: 0 crashes detected after 65s idle timeout!")
log("IPA runtime autosuspend fix is 100% VERIFIED!")
log("No crash observed in this idle window; cellular data and longer-term stability remain unverified.")
return 0
if __name__ == "__main__":