diff --git a/ports/candidate/linux-postmarketos-qcom-sdm660/0044-net-ipa-reject-unimplemented-bam-transport.patch b/ports/candidate/linux-postmarketos-qcom-sdm660/0044-net-ipa-reject-unimplemented-bam-transport.patch new file mode 100644 index 0000000..2f5a317 --- /dev/null +++ b/ports/candidate/linux-postmarketos-qcom-sdm660/0044-net-ipa-reject-unimplemented-bam-transport.patch @@ -0,0 +1,61 @@ +From: Platina Linux contributors +Subject: [PATCH] net: ipa: reject the unimplemented v2 BAM data transport + +The experimental v2.6 integration skips endpoint initialization and has no +BAM TX/RX backend. Do not publish a successful probe or count discarded +packets as successful transmissions. Reject legacy hardware before touching +registers; in particular, its BAM region must not be treated as shared SRAM +and its registers cannot use the v3.1 layout. + +Keep this guard until a real v2.6L transport is implemented and qualified. +This patch does not add cellular data support. + +--- a/drivers/net/ipa/ipa_main.c ++++ b/drivers/net/ipa/ipa_main.c +@@ -840,10 +840,11 @@ static int ipa_probe(struct platform_device *pdev) + return -EINVAL; + } + + if (data->version < IPA_VERSION_3_0) +- loader = IPA_LOADER_SKIP; +- else +- loader = ipa_firmware_loader(dev); ++ return dev_err_probe(dev, -EOPNOTSUPP, ++ "IPA v2.6L BAM data transport is not implemented\n"); ++ ++ loader = ipa_firmware_loader(dev); + if (loader == IPA_LOADER_INVALID) + return -EINVAL; + if (loader == IPA_LOADER_DEFER) +--- a/drivers/net/ipa/ipa_endpoint.c ++++ b/drivers/net/ipa/ipa_endpoint.c +@@ -1242,10 +1242,8 @@ int ipa_endpoint_skb_tx(struct ipa_endpoint *endpoint, struct sk_buff *skb) + u32 nr_frags; + int ret; + +- if (endpoint->ipa->version < IPA_VERSION_3_0) { +- dev_kfree_skb_any(skb); +- return 0; +- } ++ if (endpoint->ipa->version < IPA_VERSION_3_0) ++ return -EOPNOTSUPP; + + /* Make sure source endpoint's TLV FIFO has enough entries to + * hold the linear portion of the skb and all its fragments. +--- a/drivers/net/ipa/ipa_modem.c ++++ b/drivers/net/ipa/ipa_modem.c +@@ -139,12 +139,8 @@ ipa_start_xmit(struct sk_buff *skb, struct net_device *netdev) + goto err_drop_skb; + + endpoint = ipa->name_map[IPA_ENDPOINT_AP_MODEM_TX]; +- if (!endpoint) { +- dev_kfree_skb_any(skb); +- stats->tx_packets++; +- stats->tx_bytes += skb_len; +- return NETDEV_TX_OK; +- } ++ if (!endpoint) ++ goto err_drop_skb; + if (endpoint->config.qmap && skb->protocol != htons(ETH_P_MAP)) + goto err_drop_skb; + diff --git a/ports/candidate/linux-postmarketos-qcom-sdm660/APKBUILD b/ports/candidate/linux-postmarketos-qcom-sdm660/APKBUILD index f25fc65..7c7b480 100644 --- a/ports/candidate/linux-postmarketos-qcom-sdm660/APKBUILD +++ b/ports/candidate/linux-postmarketos-qcom-sdm660/APKBUILD @@ -3,7 +3,7 @@ maintainer="Alexey Minnekhanov " _flavor="postmarketos-qcom-sdm660" pkgname=linux-$_flavor pkgver=7.2.12 -pkgrel=21 +pkgrel=22 pkgdesc="Close to mainline linux kernel for Qualcomm Snapdragon 660 SoC" arch="aarch64" url="https://kernel.org/" @@ -80,6 +80,7 @@ source=" stable-7.2.11-12.patch 0042-arm64-dts-sdm660-add-ipa-v2-node.patch 0043-net-ipa-add-support-for-ipa-v2.6-and-sdm660.patch + 0044-net-ipa-reject-unimplemented-bam-transport.patch " _carch="arm64" @@ -179,4 +180,5 @@ d2449e4c02bf11835d20bd9c841a3b0db78ba14ebe2effaec04d98db63ea4dc41a552d23db8ae72e eb3b89ac99648776f193ee3c9d96d257f7d2e6ba5200a526e63c97e7dc4982e4b2985f15481aa4314dc54ca5f0bafb395b4f4fc375ed4fba2b8d9ca23124cd31 stable-7.2.11-12.patch d1e47d1003ec8e46febd4e980a527f48a5865f07d8e7abe27fedfbee145890b6d49ad6849950c7c611ccd75cd60722c532973cab4b650edb7602541d1df98e73 0042-arm64-dts-sdm660-add-ipa-v2-node.patch e2980a3b86521f452d042399812b8b5dd03af1193143313833e3608a8079763d4cc5c8d6c8530203db062c3df5ce40800e63567026239e6b19cdf6be07e3b199 0043-net-ipa-add-support-for-ipa-v2.6-and-sdm660.patch +feac1f55375dd9560e2e0d0e15ce1c3a916c75bea7195ff7fe9e85f6175b2e97625c0a5e6a95d0906ffbc334cfbcb609032cb9d467131fae8c8158559a319585 0044-net-ipa-reject-unimplemented-bam-transport.patch " diff --git a/project/sources.lock.json b/project/sources.lock.json index 3cc7994..e5170b9 100644 --- a/project/sources.lock.json +++ b/project/sources.lock.json @@ -16,7 +16,7 @@ "candidate": { "ports": "ports/candidate", "kernel": "7.2.12", - "kernel_package": "7.2.12-r17", + "kernel_package": "7.2.12-r22", "device_package": "5-r31", "firmware_package": "2-r5" } diff --git a/release/README.md b/release/README.md index 648e6c1..8c223b8 100644 --- a/release/README.md +++ b/release/README.md @@ -40,4 +40,4 @@ tar -xvf release/platina-linux-v0.8.1-release.tar.xz - **USB Headless SSH**: `172.16.42.1/24` with Metric 100 backup route. - **Battery Protection**: Automatically halts charging at 80% SoC, resumes below 50% SoC, 45°C thermal limit, 5% emergency sync & shutdown. - **Hexagon DSP Bringup**: `platina-dsp` boot service initializes modem remoteproc, `rmtfs`, `tqftpserv`, and `pd-mapper`. -- **EasyTier Mesh**: Auto-connects to Tokyo Oracle ARM node (`192.168.20.2`). +- **EasyTier Mesh**: Auto-connects to Tokyo Oracle ARM node. diff --git a/scripts/continue_boot_and_verify_cellular.py b/scripts/continue_boot_and_verify_cellular.py index 0c374f8..5ada5f8 100644 --- a/scripts/continue_boot_and_verify_cellular.py +++ b/scripts/continue_boot_and_verify_cellular.py @@ -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...") diff --git a/scripts/image-runtime.py b/scripts/image-runtime.py index 08558c9..c835bce 100644 --- a/scripts/image-runtime.py +++ b/scripts/image-runtime.py @@ -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', diff --git a/scripts/phone-cellular-rpmsg.py b/scripts/phone-cellular-rpmsg.py new file mode 100644 index 0000000..dd6c59c --- /dev/null +++ b/scripts/phone-cellular-rpmsg.py @@ -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()) diff --git a/scripts/phone-cellular-setup.py b/scripts/phone-cellular-setup.py index 7da6f7a..40da8d1 100755 --- a/scripts/phone-cellular-setup.py +++ b/scripts/phone-cellular-setup.py @@ -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 diff --git a/scripts/reboot_and_test_fixed_ipa.py b/scripts/reboot_and_test_fixed_ipa.py index 8393382..171a2cc 100755 --- a/scripts/reboot_and_test_fixed_ipa.py +++ b/scripts/reboot_and_test_fixed_ipa.py @@ -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__": diff --git a/tests/test_cellular_rpmsg.py b/tests/test_cellular_rpmsg.py new file mode 100644 index 0000000..22ee827 --- /dev/null +++ b/tests/test_cellular_rpmsg.py @@ -0,0 +1,252 @@ +"""Exercise AT framing, endpoint cleanup, and the experimental PPP boundary.""" +import importlib.util +import os +from pathlib import Path +import select +import socket +import subprocess +import tempfile +import threading +import unittest +from unittest.mock import MagicMock, patch + +ROOT = Path(__file__).resolve().parents[1] +spec = importlib.util.spec_from_file_location('cellular_rpmsg', ROOT / 'scripts/phone-cellular-rpmsg.py') +rpmsg = importlib.util.module_from_spec(spec) +spec.loader.exec_module(rpmsg) + + +class ATTests(unittest.TestCase): + def exchange(self, chunks, command='AT', timeout=1): + host, modem = socket.socketpair(type=socket.SOCK_DGRAM) + self.addCleanup(host.close) + self.addCleanup(modem.close) + observed = [] + + def respond(): + observed.append(modem.recv(65536)) + for data in chunks: + modem.send(data) + + thread = threading.Thread(target=respond, daemon=True) + thread.start() + result = rpmsg.at_command(host.fileno(), command, timeout) + thread.join(timeout=1) + self.assertFalse(thread.is_alive()) + self.assertEqual(observed, [command.encode() + b'\r']) + return result + + def test_split_response(self): + result = self.exchange([b'AT\r\r\nO', b'K\r\n']) + self.assertEqual(result['result'], 'OK') + + def test_connect_preserves_binary_ppp_bytes_in_same_message(self): + payload = b'\x7e\xff\x03\xc0\x21\x00\xff\x7d\x5e\x7e' + result = self.exchange([b'\r\nCONNECT\r\n' + payload], 'ATD*99#') + self.assertEqual(result['result'], 'CONNECT') + self.assertEqual(result['trailing'], b'\n' + payload) + + def test_extended_error_is_not_success(self): + result = self.exchange([b'\r\n+CME ERROR: operation not supported\r\n']) + self.assertEqual(result['result'], '+CME ERROR: operation not supported') + + def test_no_carrier(self): + result = self.exchange([b'\r\nNO CARRIER\r\n']) + self.assertEqual(result['result'], 'NO CARRIER') + + def test_ok_inside_information_line_does_not_end_response(self): + result = self.exchange([b'\r\n+INFO: OK\r\n', b'\r\nERROR\r\n']) + self.assertEqual(result['result'], 'ERROR') + + def test_timeout_is_not_success(self): + result = self.exchange([b'\r\n+CEREG: 0,2\r\n'], timeout=0.02) + self.assertEqual(result['result'], 'TIMEOUT') + + def test_reject_command_injection(self): + with self.assertRaises(ValueError): + rpmsg.at_command(-1, 'AT\rATD*99#') + + +class EndpointTests(unittest.TestCase): + def test_exclusive_session_rejects_a_second_owner(self): + with tempfile.TemporaryDirectory() as tmp: + lock = str(Path(tmp) / 'session.lock') + with rpmsg.exclusive_session(lock): + with self.assertRaisesRegex(RuntimeError, 'Another'): + with rpmsg.exclusive_session(lock): + self.fail('must not acquire an owned lock') + with rpmsg.exclusive_session(lock): + pass + + def test_existing_binding_is_preserved(self): + with tempfile.TemporaryDirectory() as tmp: + device = Path(tmp) / 'bus/rpmsg/devices/4080000.remoteproc:glink-edge.DS.-1.-1' + (device / 'driver').mkdir(parents=True) + (device / 'driver_override').write_text('existing\n') + with self.assertRaisesRegex(RuntimeError, 'already bound'): + with rpmsg.open_channel(sys_path=tmp): + self.fail('must not yield a busy endpoint') + self.assertEqual((device / 'driver_override').read_text(), 'existing\n') + + def test_endpoint_timeout_restores_override(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + device = root / 'bus/rpmsg/devices/4080000.remoteproc:glink-edge.DS.-1.-1' + driver = root / 'bus/rpmsg/drivers/rpmsg_chrdev' + device.mkdir(parents=True) + driver.mkdir(parents=True) + (device / 'driver_override').write_text('(null)\n') + with self.assertRaises(TimeoutError): + with rpmsg.open_channel(sys_path=tmp, timeout=0): + self.fail('must not yield a missing endpoint') + self.assertEqual((device / 'driver_override').read_text(), '\n') + + def test_does_not_take_over_control_channel(self): + with self.assertRaises(ValueError): + with rpmsg.open_channel('IPCRTR'): + self.fail('must not open a control channel') + + +class PPPTests(unittest.TestCase): + def test_manager_is_restored_when_modem_preparation_fails(self): + calls = [] + + def run(command, **kwargs): + calls.append(command) + if command[0] == 'qmicli': + raise subprocess.CalledProcessError(1, command) + return subprocess.CompletedProcess(command, 0) + + with patch.object(rpmsg.subprocess, 'run', side_effect=run): + with self.assertRaises(subprocess.CalledProcessError): + with rpmsg.data_session(): + self.fail('must not enter a failed data session') + self.assertIn(['rc-service', 'modemmanager', 'stop'], calls) + self.assertEqual(calls[-1], ['rc-service', 'modemmanager', 'start']) + + def test_initially_stopped_manager_stays_stopped(self): + calls = [] + + def run(command, **kwargs): + calls.append(command) + status = 3 if command == ['rc-service', 'modemmanager', 'status'] else 0 + return subprocess.CompletedProcess(command, status) + + with patch.object(rpmsg.subprocess, 'run', side_effect=run): + with rpmsg.data_session(): + pass + self.assertNotIn(['rc-service', 'modemmanager', 'stop'], calls) + self.assertNotIn(['rc-service', 'modemmanager', 'start'], calls) + + def test_dns_requires_a_matching_reply_and_binds_the_interface(self): + fake = MagicMock() + fake.__enter__.return_value = fake + fake.recv.side_effect = [b'bad', b'\x12\x34\x81\x80\x00\x01\x00\x01' + b'\x00' * 4] + with patch.object(rpmsg.socket, 'SO_BINDTODEVICE', 25, create=True), \ + patch.object(rpmsg.socket, 'socket', return_value=fake), \ + patch.object(rpmsg.os, 'urandom', return_value=b'\x12\x34'): + result = rpmsg.probe_dns('ppp0', '223.5.5.5') + fake.setsockopt.assert_called_once_with(socket.SOL_SOCKET, 25, b'ppp0\0') + fake.connect.assert_called_once_with(('223.5.5.5', 53)) + self.assertEqual(result['exit_code'], 0) + self.assertEqual(result['answers'], 1) + + def test_dns_timeouts_do_not_report_connectivity(self): + fake = MagicMock() + fake.__enter__.return_value = fake + fake.recv.side_effect = TimeoutError('timed out') + with patch.object(rpmsg.socket, 'SO_BINDTODEVICE', 25, create=True), \ + patch.object(rpmsg.socket, 'socket', return_value=fake): + result = rpmsg.probe_dns('ppp0', '223.5.5.5') + self.assertEqual(result['exit_code'], 1) + self.assertEqual(len(result['errors']), 3) + + def test_bridge_preserves_binary_data_in_both_directions(self): + host, modem = socket.socketpair(type=socket.SOCK_DGRAM) + self.addCleanup(host.close) + self.addCleanup(modem.close) + outgoing = b'\x7e\x00\xff\x7d\x5e\x01\x7e' + incoming = b'\x7e\x03\x00\xff\x7d\x5d\x7e' + received = [] + observed = [] + + def modem_peer(): + observed.append(modem.recv(65536)) + modem.send(incoming) + + class PPPPeer: + def __init__(self, command): + self.returncode = None + self.fd = os.open(command[1], os.O_RDWR | os.O_NONBLOCK | os.O_NOCTTY) + self.thread = threading.Thread(target=self.run, daemon=True) + self.thread.start() + + def run(self): + try: + os.write(self.fd, outgoing) + while self.returncode is None: + if select.select([self.fd], [], [], 0.1)[0]: + received.append(os.read(self.fd, 65536)) + if b''.join(received) == incoming: + self.returncode = 0 + finally: + os.close(self.fd) + + def poll(self): + return self.returncode + + def terminate(self): + self.returncode = -15 + + def wait(self, timeout=None): + self.thread.join(timeout) + + thread = threading.Thread(target=modem_peer, daemon=True) + thread.start() + replies = [{'result': 'OK', 'response': 'OK', 'trailing': b''} for _ in range(4)] + replies.append({'result': 'CONNECT', 'response': 'CONNECT', 'trailing': b''}) + with patch.object(rpmsg, 'at_command', side_effect=replies), \ + patch.object(rpmsg, 'wait_registration'), \ + patch.object(rpmsg.shutil, 'which', return_value='/usr/sbin/pppd'), \ + patch.object(rpmsg.subprocess, 'run', return_value=subprocess.CompletedProcess([], 0)), \ + patch.object(rpmsg.subprocess, 'Popen', side_effect=PPPPeer), \ + patch.object(rpmsg, 'interface_ipv4', return_value='10.0.0.2'), \ + patch('builtins.print'): + result = rpmsg.connect(host.fileno(), '3gnet', duration=2) + thread.join(timeout=1) + self.assertFalse(thread.is_alive()) + self.assertEqual(observed, [outgoing]) + self.assertEqual(b''.join(received), incoming) + self.assertEqual(result['bridge_tx_bytes'], len(outgoing)) + self.assertEqual(result['bridge_rx_bytes'], len(incoming)) + self.assertFalse(result['ip_connectivity']) + + def test_registration_waits_for_home_or_roaming(self): + results = [{'result': 'OK', 'response': '+CEREG: 0,2\r\n', 'trailing': b''}, + {'result': 'OK', 'response': '+CEREG: 0,5\r\n', 'trailing': b''}] + with patch.object(rpmsg, 'at_command', side_effect=results), \ + patch.object(rpmsg.time, 'sleep'), patch('builtins.print'): + rpmsg.wait_registration(-1, 1) + + def test_command_does_not_install_default_route_or_dns(self): + command = rpmsg.ppp_command('/dev/pts/5') + self.assertIn('nodefaultroute', command) + self.assertNotIn('usepeerdns', command) + self.assertNotIn('persist', command) + self.assertIn('noauth', command) + + def test_invalid_interface_rejected(self): + with self.assertRaises(ValueError): + rpmsg.ppp_command('/dev/pts/5', 'wlan0') + + def test_invalid_apn_rejected_before_any_call(self): + with self.assertRaises(ValueError): + rpmsg.connect(-1, '3gnet"\rAT+CFUN=0') + + def test_local_verification_target_is_not_an_internet_test(self): + with self.assertRaisesRegex(ValueError, 'public IPv4'): + rpmsg.connect(-1, '3gnet', verify_target='172.16.42.1') + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_cellular_setup.py b/tests/test_cellular_setup.py index 2011a41..b390173 100644 --- a/tests/test_cellular_setup.py +++ b/tests/test_cellular_setup.py @@ -207,20 +207,60 @@ class CellularSetupTests(unittest.TestCase): (driver_dir / f).touch() self.assertFalse(cellular.has_cellular_datapath(tmpdir)) - # Case 3: Driver dir has bound device symlink/dir -> True + # A bound driver alone does not establish a data transport. (driver_dir / '1e40000.ipa').mkdir() - self.assertTrue(cellular.has_cellular_datapath(tmpdir)) + self.assertFalse(cellular.has_cellular_datapath(tmpdir)) (driver_dir / '1e40000.ipa').rmdir() - # Case 4: Network interface rmnet0 exists -> True + # A named rmnet interface without backing is not enough either. net_dir = base / 'class/net' net_dir.mkdir(parents=True) (net_dir / 'lo').mkdir() (net_dir / 'usb0').mkdir() self.assertFalse(cellular.has_cellular_datapath(tmpdir)) (net_dir / 'rmnet0').mkdir() + self.assertFalse(cellular.has_cellular_datapath(tmpdir)) + + def test_datapath_rejects_legacy_ipa_and_its_rmnet_child(self): + import tempfile + with tempfile.TemporaryDirectory() as tmpdir: + base = Path(tmpdir) + device = base / 'devices/14780000.ipa' + (device / 'of_node').mkdir(parents=True) + (device / 'of_node/compatible').write_bytes(b'qcom,sdm660-ipa\0qcom,ipa-v2.6\0') + driver = base / 'bus/platform/drivers/ipa' + driver.mkdir(parents=True) + (device / 'driver').symlink_to(driver, target_is_directory=True) + net = base / 'class/net' + (net / 'rmnet_ipa0').mkdir(parents=True) + (net / 'rmnet_ipa0/device').symlink_to(device, target_is_directory=True) + (net / 'rmnet_data0').mkdir() + (net / 'rmnet_data0/lower_rmnet_ipa0').symlink_to(net / 'rmnet_ipa0', target_is_directory=True) + status = cellular.cellular_datapath_status(tmpdir) + self.assertFalse(status['ready']) + self.assertTrue(any('BAM TX/RX' in row['reason'] for row in status['interfaces'])) + # A future implemented v2 backend can opt in explicitly. + (device / 'modem').mkdir() + (device / 'modem/datapath_ready').write_text('1\n') self.assertTrue(cellular.has_cellular_datapath(tmpdir)) + def test_datapath_accepts_bound_modern_ipa(self): + import tempfile + with tempfile.TemporaryDirectory() as tmpdir: + base = Path(tmpdir) + iface = base / 'class/net/rmnet_ipa0' + (iface / 'device/driver').mkdir(parents=True) + (iface / 'device/ipa_version').write_text('3.1\n') + self.assertTrue(cellular.has_cellular_datapath(tmpdir)) + + def test_cyclic_rmnet_lowers_are_not_a_datapath(self): + import tempfile + with tempfile.TemporaryDirectory() as tmpdir: + iface = Path(tmpdir) / 'class/net/rmnet0' + iface.mkdir(parents=True) + (iface / 'lower_rmnet0').symlink_to(iface, target_is_directory=True) + self.assertFalse(cellular.has_cellular_datapath(tmpdir)) + def test_run_auto_connect_no_datapath_skips_dialing(self): recorded_calls = [] logs = [] diff --git a/tests/test_image_runtime.py b/tests/test_image_runtime.py index 93c98f0..34933c8 100644 --- a/tests/test_image_runtime.py +++ b/tests/test_image_runtime.py @@ -48,6 +48,7 @@ class ImageRuntimeTests(unittest.TestCase): self.assertTrue((self.root / 'etc/NetworkManager/dispatcher.d/90-platina-usb-power').is_file()) self.assertTrue((self.root / 'etc/NetworkManager/dispatcher.d/95-platina-mesh').is_file()) self.assertTrue((self.root / 'usr/local/sbin/platina-cellular').is_file()) + self.assertTrue((self.root / 'usr/local/sbin/platina-cellular-rpmsg').is_file()) self.assertTrue((self.root / 'usr/local/sbin/platina-mesh').is_file()) self.assertTrue((self.root / 'etc/init.d/easytier').is_file()) self.assertTrue((self.root / 'etc/easytier/easytier.conf').is_file())