diff --git a/crates/boards/src/peripheral.rs b/crates/boards/src/peripheral.rs index 7f47ffe..e783320 100644 --- a/crates/boards/src/peripheral.rs +++ b/crates/boards/src/peripheral.rs @@ -96,6 +96,10 @@ enum Touch { Packets { packet: String, }, + PacketsRequested { + packet: String, + hbpp_version: u64, + }, Gen1 { packet: String, values: [u64; 5], @@ -342,6 +346,10 @@ fn touch(data: &[u8], profile: &str, kind: &Touch) -> Result> { Touch::Z2PacketN1(board) => z2fw::from_z2_packet_n1(&mtprops()?, board)?, Touch::Z2PacketsN1(board) => z2fw::from_z2_packets_n1(&mtprops()?, board)?, Touch::Packets { packet } => z2fw::from_packets(&mtprops()?, packet)?, + Touch::PacketsRequested { + packet, + hbpp_version, + } => z2fw::from_packets_requested(&mtprops()?, packet, *hbpp_version)?, Touch::Gen1 { packet, values: [touch_maximum, prox_maximum, fll_mval, ref_clk_div, clk32_clock_enable], @@ -521,6 +529,13 @@ fn parse(raw: &catalog::Step, recipe: &Recipe) -> Result> { ], ) } + "z2fw-from-mtprops@4" => ( + touch(Touch::PacketsRequested { + packet: string("packet")?, + hbpp_version: int("hbpp_version")?, + })?, + &["hbpp_version", "packet", "profile"], + ), "z2fw-from-mtfw@1" => ( touch(Touch::Mtfw { otp_preflight: flag("otp_preflight")?, diff --git a/crates/formats/src/z2fw.rs b/crates/formats/src/z2fw.rs index 0c540ad..42d8aeb 100644 --- a/crates/formats/src/z2fw.rs +++ b/crates/formats/src/z2fw.rs @@ -371,6 +371,70 @@ pub fn from_packets(p: &Profile, packet: &str) -> Result> { Ok(container(&records)) } +/// `z2fw-from-mtprops@4`: configure the declared HBPP framing before upload, +/// then supply dynamic calibration at the boot sequence's request for it. +/// Unlike @2, calibration is not sent before the controller's setup writes. +pub fn from_packets_requested(p: &Profile, packet: &str, hbpp_version: u64) -> Result> { + if packet != "Z2" || p.packet_type() != Some(packet) || !matches!(hbpp_version, 0x103 | 0x104) { + return Err(Error("unexpected touch packet type or HBPP version")); + } + let config = p.config()?; + let nested = match config.get("Config") { + Some(c @ Value::Dict(_)) => c, + _ => &config, + }; + if nested.get("Protocol").and_then(Value::as_str) != Some("Z2") { + return Err(Error("unexpected touch protocol")); + } + let hbpp = hbpp_config(nested, false)?; + let mut words = hbpp.words.unwrap_or_else(|| le32s(&[0; 11])); + let mask = u32::from_le_bytes(words[..4].try_into().unwrap()) | (1 << 11); + words[..4].copy_from_slice(&mask.to_le_bytes()); + words[40..44].copy_from_slice(&(hbpp_version as u32).to_le_bytes()); + let mut records = vec![(CONFIG, words), (INIT, HBPP_INIT.to_vec())]; + for packet in p.firmware_list()? { + // Validate the declared framing and both checksums; keep Apple's + // packets byte-for-byte, including their load addresses. + decode_blob(packet, hbpp_version as u32)?; + records.push((SEND, packet.to_vec())); + } + let mut providers = Vec::new(); + let calibration = list(&config, "Calibration Sequence")? + .iter() + .map(|item| { + calibration_record( + field(item, "Provider")?.as_str().unwrap_or(""), + field(item, "Address")?, + field(item, "Max Size")?, + &mut providers, + ) + }) + .collect::>>()?; + if calibration.is_empty() { + return Err(Error("touch calibration sequence is empty")); + } + let mut requested = false; + for item in list(&config, "Boot Sequence")? { + if item.get("Action").and_then(Value::as_str) == Some("RequestCalibration") + && dict_len(item) == 1 + { + if requested { + return Err(Error("duplicate touch calibration request")); + } + requested = true; + records.push((SEND, REQUEST_CALIBRATION.to_vec())); + records.extend(calibration.iter().cloned()); + } else { + records.push((SEND, boot_register(item)?)); + } + } + if !requested { + return Err(Error("touch boot sequence does not request calibration")); + } + records.push((WAIT, le32s(&[hbpp.wait_ms]))); + Ok(container(&records)) +} + /// Board values `from_gen1` needs, from Apple's matching kernel personality. pub struct Gen1 { pub touch_maximum: u64, @@ -1168,6 +1232,107 @@ fn sum(d: &[u8]) -> u32 { mod tests { use super::*; + fn requested_profile(requests: usize, version: u32) -> Profile { + let request = "ActionRequestCalibration"; + let write = "Address8192Value1"; + let config = format!( + "ProtocolZ2\ + Calibration Sequence\ + Providermulti-touch-calibration\ + Address4096\ + Max Size16\ + Boot Sequence{write}{}{write}", + request.repeat(requests) + ); + Profile { + profile: Value::Dict(vec![ + ("Firmware Config".into(), Value::String(config)), + ( + "PreconstructedBootloadPacketType".into(), + Value::String("Z2".into()), + ), + ( + "Constructed Firmware".into(), + Value::Array(vec![ + Value::Data(encode_blob_for(0, b"firmware", version).unwrap()), + Value::Data(encode_blob_for(32, b"moredata", version).unwrap()), + ]), + ), + ]), + } + } + + fn read_records(data: &[u8]) -> Vec<(u32, Vec)> { + let mut pos = 8; + let mut records = Vec::new(); + while pos < data.len() { + let code = u32::from_le_bytes(data[pos..pos + 4].try_into().unwrap()); + let len = u32::from_le_bytes(data[pos + 4..pos + 8].try_into().unwrap()) as usize; + records.push((code, data[pos + 8..pos + 8 + len].to_vec())); + pos = (pos + 8 + len).div_ceil(4) * 4; + } + assert_eq!(pos, data.len()); + records + } + + #[test] + fn requested_calibration_follows_request_and_precedes_entry() { + for version in [0x103, 0x104] { + let p = requested_profile(1, version); + let data = from_packets_requested(&p, "Z2", version.into()).unwrap(); + let records = read_records(&data); + assert_eq!( + records.iter().map(|r| r.0).collect::>(), + [ + CONFIG, + INIT, + SEND, + SEND, + SEND, + SEND, + CALIBRATION, + SEND, + WAIT + ] + ); + assert_eq!(&records[0].1[..4], &(1u32 << 11).to_le_bytes()); + assert_eq!(&records[0].1[40..], &version.to_le_bytes()); + assert_eq!(records[2].1, p.firmware_list().unwrap()[0]); + assert_eq!(records[3].1, p.firmware_list().unwrap()[1]); + assert_eq!(records[5].1, REQUEST_CALIBRATION); + // A provider reference, never calibration contents. + assert_eq!(records[6].1, le32s(&[4096, 16, 0])); + // The legacy recipe retains its original command order. + let legacy = read_records(&from_packets(&p, "Z2").unwrap()); + assert_eq!( + legacy.iter().map(|r| r.0).collect::>(), + [INIT, SEND, SEND, CALIBRATION, SEND, SEND, SEND, WAIT] + ); + } + } + + #[test] + fn requested_calibration_refuses_missing_duplicate_and_bad_framing() { + for requests in [0, 2] { + assert!( + from_packets_requested(&requested_profile(requests, 0x103), "Z2", 0x103).is_err() + ); + } + let p = requested_profile(1, 0x103); + assert!(from_packets_requested(&p, "Z2", 0x104).is_err()); + assert!(from_packets_requested(&p, "Z2", 0x105).is_err()); + assert!(from_packets_requested(&p, "HIDSPI", 0x103).is_err()); + let mut p = p; + if let Value::Dict(entries) = &mut p.profile { + if let Value::Array(packets) = &mut entries[2].1 { + if let Value::Data(packet) = &mut packets[0] { + packet[12] ^= 1; + } + } + } + assert!(from_packets_requested(&p, "Z2", 0x103).is_err()); + } + #[test] fn blob_round_trip() { let packet = encode_blob(0x0010_0000, b"firmware").unwrap(); diff --git a/docs/data-and-firmware.md b/docs/data-and-firmware.md index f135840..576357f 100644 --- a/docs/data-and-firmware.md +++ b/docs/data-and-firmware.md @@ -75,6 +75,17 @@ and they are kept in the cache by their SHA-256. `install` builds a board's peripheral firmware by itself. +The `z2fw-from-mtprops@4` peripheral step takes `input`, `profile`, +`packet = "Z2"` and `hbpp_version` (259 or 260). It checks each packet +against that HBPP framing, writes configuration before upload, and inserts +dynamic calibration records immediately after the sole RequestCalibration +item in the boot sequence. A missing or repeated request is refused. The +older `@2` output and order are unchanged. The kernel must honor the +container's HBPP configuration word for dynamic calibration: CONFIG's +validity mask bit 11 selects zero-based word 10, which holds 0x103 (full +payload word count) or 0x104 (word count minus one). The D21 backend keeps +its existing minus-one behavior when that bit is absent. + ## Firmware keys Boot firmware is built from Apple's, which is encrypted. The keys