Files
bananarchy/scripts/check-lk2nd-beatles.py
T

472 lines
19 KiB
Python
Executable File

#!/usr/bin/env python3
"""Validate the source-built nokia-beatles lk2nd boot image.
The 2720's MSM8905 is a partial-goods (2-core) part. Its stock aboot calls
update_partial_goods_dtb_nodes() on the QCDT-selected DTB and ASSERTs when
/cpus, /cpus/cpu@2 or /cpus/cpu@3 (with a 4-byte device_type) is missing:
"Failed to get parent node: /cpus" then "panic: ASSERT FAILED at
(platform/msm_shared/partial_goods.c:80): 0". Upstream lk2nd DTBs have no
/cpus, so every lk2nd image crashed into Sahara memory-debug EDL before lk2nd
ran. The port adds /cpus to the common dtsi (all QCDT DTBs) plus a compact
/lk2nd/nokia-beatles node in the existing msm8905-qrd-skub DTB.
Checks (all offline, pure Python):
* Android boot.img header, cmdline and SEANDROIDENFORCE trailer.
* QCDT v2 exact 2720 entry (0x14b / 0x1000b / 0x100 / 0) and the QRD
fallback entry (0x14b / 0xb / 0x100); both must share one DTB.
* Every unique QCDT DTB has /cpus/cpu@2 and /cpus/cpu@3 with a 4-byte
device_type (the partial-goods ASSERT fix).
* The selected DTB's stock root IDs and the beatles device node.
* The beatles device node: model, compatible, match-panel, dtb-files and
all three aboot panel names, with the GC9305 v2 panel init stream.
* The patch and the shared parser header in the repo are in sync.
Use --emit-streams-header PATH to generate a C array for the host unit test
bootloader/lk2nd/test_spi_panel_init.c.
"""
import argparse
import os
import struct
import sys
BOOT_MAGIC = b"ANDROID!"
QCDT_MAGIC = b"QCDT"
FDT_MAGIC = 0xd00dfeed
FDT_BEGIN_NODE = 1
FDT_END_NODE = 2
FDT_PROP = 3
FDT_NOP = 4
FDT_END = 9
STOCK_PLATFORM_ID = 0x14b
STOCK_VARIANT_ID = 0x1000b
STOCK_SUBTYPE = 0x100
STOCK_SOC_REV = 0
FALLBACK_VARIANT_ID = 0xb
BOARD_ID = [FALLBACK_VARIANT_ID, STOCK_SUBTYPE,
STOCK_VARIANT_ID, STOCK_SUBTYPE]
PANEL_NAMES = (
"qcom,mdss_spi_gc9305_qvga_cmd",
"qcom,mdss_spi_gc9305_v2_qvga_cmd",
"qcom,mdss_spi_gc9305_3rd_qvga_cmd",
)
INIT_PANEL = PANEL_NAMES[1]
EXPECTED_CMDS = 10
RGB565 = bytes([0x3a, 0x05])
COLUMN_WINDOW = bytes([0x2a, 0x00, 0x00, 0x00, 0xef])
ROW_WINDOW = bytes([0x2b, 0x00, 0x00, 0x01, 0x3f])
def align(value, page):
return (value + page - 1) // page * page
def fdt_nodes(data):
vals = struct.unpack_from(">10I", data, 0)
magic, totalsize, off_struct, off_strings, _, version = vals[:6]
size_strings, size_struct = vals[8], vals[9]
if magic != FDT_MAGIC or version not in (16, 17):
raise ValueError("invalid FDT header")
strings = data[off_strings:off_strings + size_strings]
nodes = {}
stack = []
pos = off_struct
while True:
token = struct.unpack_from(">I", data, pos)[0]
pos += 4
if token == FDT_BEGIN_NODE:
end = data.index(b"\0", pos)
name = data[pos:end].decode("utf-8", "replace")
pos = (end + 4) & ~3
if not stack:
path = "/"
elif stack[-1] == "/":
path = "/" + name
else:
path = stack[-1] + "/" + name
stack.append(path)
nodes[path] = {}
elif token == FDT_END_NODE:
stack.pop()
if not stack:
break
elif token == FDT_PROP:
length, nameoff = struct.unpack_from(">II", data, pos)
pos += 8
value = data[pos:pos + length]
pos = (pos + length + 3) & ~3
end = strings.index(b"\0", nameoff)
prop = strings[nameoff:end].decode("utf-8", "replace")
nodes[stack[-1]][prop] = value
elif token == FDT_NOP:
continue
elif token == FDT_END:
break
else:
raise ValueError("bad FDT token 0x%x" % token)
return nodes, totalsize
def prop_str(nodes, path, prop):
return nodes.get(path, {}).get(prop, b"").rstrip(b"\0").decode("utf-8", "replace")
def prop_cells(nodes, path, prop):
raw = nodes.get(path, {}).get(prop, b"")
return list(struct.unpack(">%dI" % (len(raw) // 4), raw[:len(raw) // 4 * 4]))
def parse_stream(raw):
"""Return (commands, total_delay) or raise ValueError."""
off = 0
commands = []
total_delay = 0
while off + 2 <= len(raw):
wait, dlen = raw[off], raw[off + 1]
off += 2
if not dlen or off + dlen > len(raw):
raise ValueError("malformed command at byte %d" % (off - 2))
payload = raw[off:off + dlen]
off += dlen
commands.append((wait, payload))
total_delay += wait
if off != len(raw):
raise ValueError("trailing garbage at byte %d" % off)
return commands, total_delay
def check_stream(name, raw, problems):
try:
commands, total_delay = parse_stream(raw)
except ValueError as exc:
problems.append("%s panel init stream: %s" % (name, exc))
return None
if len(commands) != EXPECTED_CMDS:
problems.append("%s panel init has %d commands, expected %d" %
(name, len(commands), EXPECTED_CMDS))
if total_delay != 120:
problems.append("%s panel init waits %d ms total, expected 120" %
(name, total_delay))
payloads = [payload for _, payload in commands]
for label, want in (("RGB565 COLMOD", RGB565),
("240 column window", COLUMN_WINDOW),
("320 row window", ROW_WINDOW)):
if want not in payloads:
problems.append("%s panel init is missing the %s command" % (name, label))
if b"\x11" not in payloads:
problems.append("%s panel init is missing sleep-out (0x11)" % name)
if b"\x29" not in payloads:
problems.append("%s panel init is missing display-on (0x29)" % name)
if not payloads or payloads[-1] != b"\x2c":
problems.append("%s panel init does not end with RAMWR (0x2c)" % name)
return commands
def check_device_node(nodes, label, problems):
prefix = "%s: " % label
if prop_cells(nodes, "/", "qcom,msm-id")[:2] != [STOCK_PLATFORM_ID, 0]:
problems.append(prefix + "qcom,msm-id is not the stock 0x14b/0")
board = prop_cells(nodes, "/", "qcom,board-id")
if board != BOARD_ID:
problems.append(prefix + "qcom,board-id is %r, expected %r" % (board, BOARD_ID))
if "/chosen" not in nodes:
problems.append(prefix + "missing /chosen")
if not any(props.get("device_type") == b"memory\0" for props in nodes.values()):
problems.append(prefix + "missing /memory node")
subnodes = sorted(p for p in nodes if p.startswith("/lk2nd/") and
p.count("/") == 2)
for needed in ("/lk2nd/cat-b35", "/lk2nd/nokia-argon",
"/lk2nd/nokia-beatles"):
if needed not in subnodes:
problems.append(prefix + "missing %s (upstream node lost)" % needed)
node = "/lk2nd/nokia-beatles"
if node not in nodes:
problems.append(prefix + "missing /lk2nd/nokia-beatles")
return None
props = nodes[node]
if prop_str(nodes, node, "model") != "Nokia 2720 Flip":
problems.append(prefix + "wrong model %r" % prop_str(nodes, node, "model"))
if prop_str(nodes, node, "compatible") != "nokia,beatles":
problems.append(prefix + "wrong compatible %r" %
prop_str(nodes, node, "compatible"))
if "lk2nd,match-panel" not in props:
problems.append(prefix + "beatles node lost lk2nd,match-panel")
if prop_str(nodes, node, "lk2nd,dtb-files") != "msm8905-nokia-beatles":
problems.append(prefix + "wrong lk2nd,dtb-files %r" %
prop_str(nodes, node, "lk2nd,dtb-files"))
stream = None
for name in PANEL_NAMES:
panel = node + "/panel/" + name
if panel not in nodes:
problems.append(prefix + "missing panel node %s" % name)
continue
if name == INIT_PANEL:
if "lk2nd,panel-init" not in nodes[panel]:
problems.append(prefix + "panel %s has no lk2nd,panel-init" % name)
else:
stream = nodes[panel]["lk2nd,panel-init"]
check_stream(name, stream, problems)
elif "lk2nd,panel-init" in nodes[panel]:
problems.append(prefix + "panel %s must stay compact (no init stream)" % name)
return stream
def extract_patch_file(patch_text, path):
"""Return the added-file body for a 'new file' diff section."""
marker = "diff --git a/%s b/%s\n" % (path, path)
start = patch_text.find(marker)
if start < 0:
return None
lines = patch_text[start:].split("\n")
out = []
started = False
for line in lines[1:]:
if line.startswith("@@"):
started = True
continue
if not started:
continue
if line.startswith("diff --git "):
break
if line.startswith("+"):
out.append(line[1:])
return "\n".join(out) + "\n"
def main():
base = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument("--image", default=os.path.join(base, "images", "boot-lk2nd-nokia-beatles.img"))
ap.add_argument("--patch", default=os.path.join(base, "bootloader", "lk2nd", "nokia-beatles.patch"))
ap.add_argument("--emit-streams-header", default=None,
help="write the panel init stream as a C array for the host unit test")
ap.add_argument("--expect-fastboot", type=int, choices=(0, 1), default=0,
help="require (1) or forbid (0) the forced-fastboot diagnostic build")
ap.add_argument("--expect-display", type=int, choices=(0, 1), default=0,
help="require (1) or forbid (0) the boot-time SPI display build")
ap.add_argument("--allow-missing-cookie", action="store_true",
help="allow the known-good display image built before the low-bit reboot cookie")
args = ap.parse_args()
problems = []
if not os.path.isfile(args.image):
print("FAIL: missing %s" % args.image)
return 1
data = open(args.image, "rb").read()
if data[:8] != BOOT_MAGIC:
print("FAIL: %s is not an Android boot image" % args.image)
return 1
hdr = struct.unpack_from("<8s10I", data, 0)
kernel_size, kernel_addr, ramdisk_size, ramdisk_addr = hdr[1:5]
second_size, second_addr, tags_addr, page = hdr[5:9]
dt_size = hdr[9]
if page != 2048:
problems.append("page size is %d, expected 2048" % page)
if kernel_addr != 0x80008000:
problems.append("kernel load address %#x is not the stock 0x80008000" % kernel_addr)
if dt_size == 0 or dt_size % page != 0:
problems.append("dt_size %d is not a page-multiple QCDT image" % dt_size)
cmdline = data[64:576].split(b"\0")[0].decode("utf-8", "replace")
cmd_parts = cmdline.split(" ")
if cmd_parts[:2] != ["lk2nd", "lk2nd.compatible=nokia,beatles"] or \
any(p not in ("lk2nd.force-panel-init", "lk2nd.no-display",
"lk2nd.display=on") for p in cmd_parts[2:]):
problems.append("cmdline is %r" % cmdline)
no_display = "lk2nd.no-display" in cmd_parts[2:]
display_on = "lk2nd.display=on" in cmd_parts[2:]
if args.expect_fastboot and not no_display:
problems.append("diagnostic image must carry lk2nd.no-display")
if args.expect_display and not display_on:
problems.append("display image must carry lk2nd.display=on")
if args.expect_display and no_display:
problems.append("display image must not carry lk2nd.no-display")
if not args.expect_display and display_on:
problems.append("non-display image must not carry lk2nd.display=on")
forced_fastboot = b"Fastboot mode was forced with compile-time flag." in data
if forced_fastboot != bool(args.expect_fastboot):
problems.append("fastboot diagnostic marker is %s, expected %s" %
(forced_fastboot, bool(args.expect_fastboot)))
for marker in (b"lk2nd.no-display", b"lk2nd.display=on",
b"oem scan-boot", b"oem display-init", b"oem display-test",
b"oem scan-dtb", b"QUP output FIFO timeout",
b"SPI panel %s: keeping aboot continuous splash",
b"SPI display ready",
b"scan-only: final kernel cmdline/DTB ready",
b"No valid pstore console",
b"SPI panel fallback from QCDT: %s",
b"offset is not block-aligned",
b"aligned read exceeds partition"):
if marker not in data:
problems.append("binary is missing %r" % marker.decode("ascii", "replace"))
if not args.allow_missing_cookie and \
b"beatles low-bit reboot cookie" not in data:
problems.append("binary is missing b'beatles low-bit reboot cookie'")
if not data.endswith(b"SEANDROIDENFORCE"):
problems.append("missing SEANDROIDENFORCE trailer")
qcdt_off = (page + align(kernel_size, page) + align(ramdisk_size, page) +
align(second_size, page))
entries = {}
if data[qcdt_off:qcdt_off + 4] != QCDT_MAGIC:
problems.append("no QCDT table at offset %d" % qcdt_off)
else:
_, version, num_entries = struct.unpack_from("<4sII", data, qcdt_off)
if version != 2:
problems.append("QCDT version is %d, expected 2" % version)
for i in range(num_entries):
off = qcdt_off + 12 + 24 * i
platform_id, variant_id, subtype, soc_rev, dtb_off, dtb_size = \
struct.unpack_from("<6I", data, off)
if (platform_id == STOCK_PLATFORM_ID and soc_rev == STOCK_SOC_REV and
subtype == STOCK_SUBTYPE and
variant_id in (STOCK_VARIANT_ID, FALLBACK_VARIANT_ID)):
entries[variant_id] = (dtb_off, dtb_size, i)
for variant, label in ((STOCK_VARIANT_ID, "exact 2720"),
(FALLBACK_VARIANT_ID, "QRD fallback")):
if variant not in entries:
problems.append("QCDT has no %s entry" % label)
if len(entries) == 2:
exact, fallback = entries[STOCK_VARIANT_ID], entries[FALLBACK_VARIANT_ID]
if exact[:2] != fallback[:2]:
problems.append("the two 2720 QCDT entries must share the same DTB")
# Every QCDT DTB must survive aboot's partial-goods DTB patch.
seen_offsets = {}
for i in range(num_entries):
off = qcdt_off + 12 + 24 * i
_, _, _, _, dtb_off, dtb_size = struct.unpack_from("<6I", data, off)
if dtb_off and dtb_size:
seen_offsets.setdefault(dtb_off, dtb_size)
for dtb_off, dtb_size in seen_offsets.items():
dtb = data[qcdt_off + dtb_off:qcdt_off + dtb_off + dtb_size]
if dtb[:4] != b"\xd0\x0d\xfe\xed":
continue
try:
nodes, _ = fdt_nodes(dtb)
except ValueError:
continue
if "/cpus" not in nodes:
problems.append("QCDT DTB@0x%x lacks /cpus (aboot partial-goods ASSERT)" %
dtb_off)
continue
for cpu in ("cpu@2", "cpu@3"):
path = "/cpus/" + cpu
if path not in nodes:
problems.append("QCDT DTB@0x%x lacks %s" % (dtb_off, path))
elif nodes[path].get("device_type") != b"cpu\0":
problems.append("QCDT DTB@0x%x %s device_type is %r, expected b'cpu\\0'" %
(dtb_off, path, nodes[path].get("device_type")))
stream = None
if STOCK_VARIANT_ID in entries:
dtb_off, dtb_size, _ = entries[STOCK_VARIANT_ID]
dtb = data[qcdt_off + dtb_off:qcdt_off + dtb_off + dtb_size]
if dtb[:4] != b"\xd0\x0d\xfe\xed":
problems.append("2720 DTB is not an FDT")
else:
try:
nodes, totalsize = fdt_nodes(dtb)
if totalsize > dtb_size:
problems.append("2720 DTB is truncated (%d > %d)" %
(totalsize, dtb_size))
stream = check_device_node(nodes, "2720 DTB", problems)
except ValueError as exc:
problems.append("2720 DTB: %s" % exc)
# The shared parser header is stored verbatim in the repo for the host test.
header_path = os.path.join(base, "bootloader", "lk2nd", "spi-panel-init.h")
if not os.path.isfile(args.patch):
problems.append("missing source patch %s" % args.patch)
elif not os.path.isfile(header_path):
problems.append("missing %s" % header_path)
else:
patch_text = open(args.patch, "r").read()
want = open(header_path, "r").read()
got = extract_patch_file(patch_text, "lk2nd/include/lk2nd/spi-panel-init.h")
if got != want:
problems.append("bootloader/lk2nd/spi-panel-init.h is out of sync with the patch")
for needed in (
"app/aboot/aboot.c",
"lk2nd/boot/extlinux.c",
"lk2nd/device/2nd/scan-boot.c",
"lk2nd/device/dts/lk2nd.dtsi",
"lk2nd/device/dts/msm8909/nokia-beatles.dtsi",
"lk2nd/device/dts/msm8909/msm8905-qrd-skub.dts",
"lk2nd/device/2nd/spi-display.c",
"lk2nd/fastboot/fetch.c",
"platform/msm_shared/mdss_spi.c",
"platform/msm_shared/reboot.c",
):
if "diff --git a/%s b/%s" % (needed, needed) not in patch_text:
problems.append("patch is missing %s" % needed)
if "mdss_spi_panel_init_commands" not in patch_text or \
"lk2nd,panel-init" not in patch_text:
problems.append("patch is missing the panel initialization code")
if "diff --git a/lk2nd/device/dts/lk2nd.dtsi" not in patch_text:
problems.append("patch is missing the /cpus fix in lk2nd.dtsi")
if "oem scan-boot" not in patch_text:
problems.append("patch is missing the oem scan-boot diagnostic command")
if "diff --git a/lk2nd/ramoops/ramoops.c" not in patch_text:
problems.append("patch is missing the always-on ramoops console fix")
if "scan-only: final kernel cmdline/DTB ready" not in patch_text:
problems.append("patch is missing the final-DTB scan-only hook")
if "No valid pstore console" not in patch_text:
problems.append("patch is missing ramoops console validation")
if "SPI panel fallback from QCDT" not in patch_text:
problems.append("patch is missing the chain-loaded panel fallback")
if "per-word SPEW log" not in patch_text:
problems.append("patch is missing the QUP log flood fix")
if "offset is not block-aligned" not in patch_text:
problems.append("patch is missing the block-safe read-partition guard")
for needed in (
"diff --git a/platform/msm_shared/spi_qup.c" in patch_text,
"diff --git a/platform/msm_shared/clock_lib2.c" in patch_text,
):
if not needed:
problems.append("patch is missing a bounded QUP/clock poll")
if "oem display-init" not in patch_text:
problems.append("patch is missing the runtime display probe")
if "lk2nd.display=on" not in patch_text:
problems.append("patch is missing the boot-time display option")
if "platform/msm_shared/reboot.c" not in patch_text or \
"beatles low-bit reboot cookie" not in patch_text:
problems.append("patch is missing the low-bit lk2nd menu reboot cookie")
if problems:
for problem in problems:
print("FAIL: %s" % problem)
return 1
print("[ok] source-built beatles lk2nd (%s): cmdline=%r, %d bytes, "
"dt_size=%d, both 0x14b entries -> DTB@0x%x" %
("diagnostic" if args.expect_fastboot else
"display" if args.expect_display else "normal",
cmdline, len(data), dt_size, entries[STOCK_VARIANT_ID][0]))
print("[ok] all %d QCDT DTBs have /cpus/cpu@2 and cpu@3 (partial-goods fix)" %
len(seen_offsets))
print("[ok] 2720 DTB keeps the upstream board-id order and carries the "
"beatles node with the GC9305 v2 panel init stream")
print("[ok] patch/header in sync")
if args.emit_streams_header:
out = ["/* generated by scripts/check-lk2nd-beatles.py */",
"#ifndef PANEL_STREAMS_H", "#define PANEL_STREAMS_H", "",
"static const unsigned char stream_v2[] = {"]
for i in range(0, len(stream), 12):
out.append(" " + ", ".join("0x%02x" % x for x in stream[i:i + 12]) + ",")
out += ["};", "", "#endif"]
with open(args.emit_streams_header, "w") as fh:
fh.write("\n".join(out) + "\n")
print("[ok] wrote %s" % args.emit_streams_header)
return 0
if __name__ == "__main__":
sys.exit(main())