From fdb999e5a5043108abf4a6fc2dba51f7b7e082e5 Mon Sep 17 00:00:00 2001 From: Scott Jones Date: Sun, 25 Oct 2026 17:17:54 -0300 Subject: [PATCH] iio: common: aop_sensors: Publish CT720 color channels The CT720 (FireFish2) report already carries four channel counts and a correlated color temperature beside the lux float at +0x1d. The driver registered one channel for that part, so those fields never reached sysfs. Publish red, green, blue, and clear counts plus color temperature on aop-sensors-als when the part is the CT720. Color is accepted only when both integration-time copies match, are non-zero, and are at most 10000000. A report that fails that gate still publishes lux, and the color channels then read ENODATA rather than a stale sample. VD6286, CT817, and the lid-angle sensor keep the channels they had. Covered J313 readings still had the firmware CCT byte set at clear counts of 11 and below, and the published temperatures were 788 K, 1288 K, 2904 K and 6781 K. Publish the temperature only when clear is at least 12. Red, green, blue, and clear stay published. Checked against three captured J313 reports with an offline mirror of the integer conversion. Not run on hardware. Based on a patch by Lucas Goossen (omacom/linux-aurora#220), commits b5677f76fdc and 88c4f98faa0 there, rewritten for this tree. [7.3 base: rewritten on this tree's N-channel helper, which already publishes the VD6286's color temperature, in place of the seqlock slot table the original added. The helper gains a per-channel spec (modifier and info mask) for the four intensity channels, and a channel_withdrawn() hook so a report can take a channel's last reading back; the decode, the gates and the offsets are the original's. Each channel is published on its own, so a reader can see counts from two adjacent reports. aop-als-channel-tests.py covers the CT720 layout, the gates and six mutants. Built; not run on hardware.] Co-Authored-By: Claude Fable 5.2 Signed-off-by: Scott Jones --- drivers/iio/common/aop_sensors/aop_als.rs | 140 +++++++++++++++++++++- rust/bindings/bindings_helper.h | 5 + rust/kernel/iio/common/aop_sensors.rs | 74 +++++++++--- tools/asahi/aop-als-channel-tests.py | 58 +++++++++ 4 files changed, 262 insertions(+), 15 deletions(-) diff --git a/drivers/iio/common/aop_sensors/aop_als.rs b/drivers/iio/common/aop_sensors/aop_als.rs index e64f7ff26a6e0..b19c4d9b18c8c 100644 --- a/drivers/iio/common/aop_sensors/aop_als.rs +++ b/drivers/iio/common/aop_sensors/aop_als.rs @@ -8,7 +8,9 @@ use kernel::{ bindings, c_str, device::Core, firmware::Firmware, - iio::common::aop_sensors::{AopSensorData, IIORegistration, MessageProcessor, MICRO}, + iio::common::aop_sensors::{ + AopSensorData, ChannelSpec, IIORegistration, MessageProcessor, MICRO, + }, module_platform_driver, of, platform, prelude::*, soc::apple::aop::{EPICService, FakehidRegistration, AOP}, @@ -172,6 +174,72 @@ fn f32_to_micro(f: u32) -> Option { }) } +// FireFish2 / CT720 report, 55 bytes, lux float at +0x1d. The four counts are +// red, green, blue, clear. Clear is the wideband count (largest in room light; +// the calibration gains are 8, 8, 8, 4). Under the ~5460 K light captured on +// a J313 the first three ranked green, red, blue. Byte +0x2a is non-zero +// when the color temperature at +0x2b is valid. The integration time is stored +// twice at +0x2f (the AOP logs 197380 µs when it arms this sensor); disagreeing +// copies mean this is not that layout, and color is left unpublished. +const CT720_LEN: usize = 55; +const CT720_COUNT_OFF: [usize; 4] = [0x0d, 0x11, 0x15, 0x19]; +const CT720_CCT_FLAG: usize = 0x2a; +const CT720_CCT_OFF: usize = 0x2b; +const CT720_INTEG_OFF: usize = 0x2f; +const CT720_INTEG_MAX: u32 = 10_000_000; +/// Clear counts at or below 11 on a covered J313 still had the firmware CCT +/// byte set, and the published temperatures were 788 K, 1288 K, 2904 K and +/// 6781 K. Publish CCT only when clear is at least this. Not hardware-tested. +const CT720_CCT_MIN_CLEAR: u32 = 12; + +/// Channels of a CT720. Channel 0 is the lux channel every part has. +const CT720_RED: usize = 1; +const CT720_CLEAR: usize = 4; +const CT720_CCT: usize = 5; +const CT720_CHANS: usize = 6; + +fn u32_at(message: &[u8], off: usize) -> Option { + let b = message.get(off..off + 4)?; + Some(u32::from_le_bytes([b[0], b[1], b[2], b[3]])) +} + +/// Whether a CT720 report has the layout the color fields are read from. +fn ct720_layout(message: &[u8]) -> bool { + if message.len() < CT720_LEN { + return false; + } + match ( + u32_at(message, CT720_INTEG_OFF), + u32_at(message, CT720_INTEG_OFF + 4), + ) { + (Some(integ), Some(again)) => integ != 0 && integ == again && integ <= CT720_INTEG_MAX, + _ => false, + } +} + +/// A color channel of a CT720 report: a count in whole units, or the color temperature. +fn ct720_color(message: &[u8], channel: usize) -> Option { + if !ct720_layout(message) { + return None; + } + if (CT720_RED..=CT720_CLEAR).contains(&channel) { + let count = u32_at(message, CT720_COUNT_OFF[channel - CT720_RED])?; + return Some(u64::from(count).saturating_mul(MICRO)); + } + if channel != CT720_CCT || message.get(CT720_CCT_FLAG).copied() == Some(0) { + return None; + } + if u32_at(message, CT720_COUNT_OFF[CT720_CLEAR - CT720_RED])? < CT720_CCT_MIN_CLEAR { + return None; + } + let bits = u32_at(message, CT720_CCT_OFF)?; + if bits & 0x8000_0000 != 0 { + return None; + } + // Zero does not describe a colour temperature. + f32_to_micro(bits).filter(|value| *value != 0) +} + struct MsgProc(usize); fn report_float(message: &[u8], offset: usize) -> Option { @@ -191,9 +259,18 @@ impl MessageProcessor for MsgProc { // Zero and negative CCT do not describe a colour temperature. report_float(message, CCT_OFFSET_VD6286).filter(|value| *value != 0) } + _ if self.0 == LUX_OFFSET_CT720 => ct720_color(message, channel), _ => None, } } + + /// A CT720 report that carries lux but not a color channel (another layout, no valid + /// color temperature, too little light for one) withdraws that channel's last reading: + /// it reads `ENODATA` rather than a stale color. A report with no lux reading leaves + /// every channel as it was. + fn channel_withdrawn(&self, message: &[u8], channel: usize) -> bool { + self.0 == LUX_OFFSET_CT720 && channel != 0 && self.process(message).is_some() + } } enum AlsIio { @@ -203,6 +280,59 @@ enum AlsIio { Color { _registration: IIORegistration, }, + Ct720 { + _registration: IIORegistration, + }, +} + +/// Lux and color temperature are processed values; the four counts are raw. +fn ct720_channels() -> [ChannelSpec; CT720_CHANS] { + let raw = 1 << bindings::BINDINGS_IIO_CHAN_INFO_RAW; + let processed = 1 << bindings::BINDINGS_IIO_CHAN_INFO_PROCESSED; + let count = |modifier| ChannelSpec { + ty: bindings::BINDINGS_IIO_INTENSITY, + modifier: Some(modifier), + info_mask: raw, + }; + [ + ChannelSpec { + ty: bindings::BINDINGS_IIO_LIGHT, + modifier: None, + info_mask: processed, + }, + count(bindings::BINDINGS_IIO_MOD_LIGHT_RED), + count(bindings::BINDINGS_IIO_MOD_LIGHT_GREEN), + count(bindings::BINDINGS_IIO_MOD_LIGHT_BLUE), + count(bindings::BINDINGS_IIO_MOD_LIGHT_CLEAR), + ChannelSpec { + ty: bindings::BINDINGS_IIO_COLORTEMP, + modifier: None, + info_mask: processed, + }, + ] +} + +fn register_ct720( + pdev: &platform::Device, + aop: &Arc, + service: EPICService, + offset: usize, +) -> Result<(FakehidRegistration, IIORegistration)> { + let channels = ct720_channels(); + let data = AopSensorData::new_channels( + pdev.as_ref().into(), + channels.map(|channel| channel.ty), + MsgProc(offset), + )?; + let listener = FakehidRegistration::new(aop.clone(), service, data.clone())?; + enable_als(aop.as_ref(), pdev, &service, offset)?; + let iio = IIORegistration::new_specs( + data, + c"aop-sensors-als", + channels, + kernel::module::this_module::(), + )?; + Ok((listener, iio)) } struct IIOAopAlsDriver { @@ -276,6 +406,14 @@ impl platform::Driver for IIOAopAlsDriver { _registration: registration, }, ) + } else if offset == LUX_OFFSET_CT720 { + let (listener, registration) = register_ct720(pdev, &adata, service, offset)?; + ( + listener, + AlsIio::Ct720 { + _registration: registration, + }, + ) } else { let (listener, registration) = register_channels(pdev, &adata, service, offset, [ty])?; ( diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helper.h index 01e0e6cfbced8..db35f964be4b6 100644 --- a/rust/bindings/bindings_helper.h +++ b/rust/bindings/bindings_helper.h @@ -178,6 +178,11 @@ const u32 BINDINGS_IIO_CHAN_INFO_SCALE = IIO_CHAN_INFO_SCALE; const u32 BINDINGS_IIO_ANGL = IIO_ANGL; const u32 BINDINGS_IIO_LIGHT = IIO_LIGHT; const u32 BINDINGS_IIO_COLORTEMP = IIO_COLORTEMP; +const u32 BINDINGS_IIO_INTENSITY = IIO_INTENSITY; +const u32 BINDINGS_IIO_MOD_LIGHT_RED = IIO_MOD_LIGHT_RED; +const u32 BINDINGS_IIO_MOD_LIGHT_GREEN = IIO_MOD_LIGHT_GREEN; +const u32 BINDINGS_IIO_MOD_LIGHT_BLUE = IIO_MOD_LIGHT_BLUE; +const u32 BINDINGS_IIO_MOD_LIGHT_CLEAR = IIO_MOD_LIGHT_CLEAR; const u32 BINDINGS_IIO_ACCEL = IIO_ACCEL; const u32 BINDINGS_IIO_ANGL_VEL = IIO_ANGL_VEL; const u32 BINDINGS_IIO_ROT = IIO_ROT; diff --git a/rust/kernel/iio/common/aop_sensors.rs b/rust/kernel/iio/common/aop_sensors.rs index dfd42f01a582e..f6f0c27c792e6 100644 --- a/rust/kernel/iio/common/aop_sensors.rs +++ b/rust/kernel/iio/common/aop_sensors.rs @@ -57,6 +57,25 @@ pub trait MessageProcessor: Send + Sync { None } } + + /// Whether `message` says that `channel` has no reading any more, so that the reading it + /// last had must stop being reported: reads return `ENODATA` until the next one arrives. + /// It is asked only when [`Self::process_channel`] returned `None` for the same message. + fn channel_withdrawn(&self, _message: &[u8], _channel: usize) -> bool { + false + } +} + +/// One IIO channel of a sensor: its type, an optional modifier (`IIO_MOD_*`) and the +/// `info_mask_separate` bits it answers. +#[derive(Clone, Copy)] +pub struct ChannelSpec { + /// The `IIO_*` channel type. + pub ty: u32, + /// The `IIO_MOD_*` modifier of a modified channel. + pub modifier: Option, + /// The `IIO_CHAN_INFO_*` bits of the channel. + pub info_mask: usize, } /// The state shared between a sensor's report listener and its IIO device: the latest reading. @@ -104,6 +123,8 @@ impl FakehidListener for AopSensorData IIORegistration { info_mask: usize, module: &ThisModule, ) -> Result { - if ty != data.ty { + Self::new_specs( + data, + name, + ty.map(|ty| ChannelSpec { + ty, + modifier: None, + info_mask, + }), + module, + ) + } + + /// Registers the sensor's channels, each with its own modifier and info mask. The types + /// must match those of `data`. + pub fn new_specs( + data: Arc>, + name: &'static CStr, + channels: [ChannelSpec; N], + module: &ThisModule, + ) -> Result { + if channels.map(|channel| channel.ty) != data.ty { return Err(EINVAL); } let spec = KBox::pin( IIOSpec { - spec: core::array::from_fn(|channel| bindings::iio_chan_spec { - type_: ty[channel], - address: channel as _, - __bindgen_anon_1: bindings::iio_chan_spec__bindgen_ty_1 { - scan_type: bindings::iio_scan_type { - __bindgen_anon_1: bindings::iio_scan_type__bindgen_ty_1 { - format: b'u' as _, + spec: core::array::from_fn(|channel| { + let mut spec = bindings::iio_chan_spec { + type_: channels[channel].ty, + channel2: channels[channel].modifier.unwrap_or(0) as _, + address: channel as _, + __bindgen_anon_1: bindings::iio_chan_spec__bindgen_ty_1 { + scan_type: bindings::iio_scan_type { + __bindgen_anon_1: bindings::iio_scan_type__bindgen_ty_1 { + format: b'u' as _, + }, + realbits: 32, + storagebits: 32, + ..Default::default() }, - realbits: 32, - storagebits: 32, - ..Default::default() }, - }, - info_mask_separate: info_mask, - ..Default::default() + info_mask_separate: channels[channel].info_mask, + ..Default::default() + }; + spec.set_modified(channels[channel].modifier.is_some() as _); + spec }), vtable: bindings::iio_info { read_raw: Some(aop_read_raw::), diff --git a/tools/asahi/aop-als-channel-tests.py b/tools/asahi/aop-als-channel-tests.py index d3f5f3ed48d87..14129510438b5 100644 --- a/tools/asahi/aop-als-channel-tests.py +++ b/tools/asahi/aop-als-channel-tests.py @@ -119,6 +119,58 @@ def source(): assert_eq!(f32_to_micro((-0.25f32).to_bits()),Some(0)); assert_eq!(f32_to_micro(1u32),Some(0)); } +fn ct720(counts:[u32;4],flag:u8,cct:f32,integ:(u32,u32),lux:f32)->[u8;55] { + let mut report=[0u8;55]; + for (i,count) in counts.iter().enumerate() { report[0x0d+4*i..0x11+4*i].copy_from_slice(&count.to_le_bytes()); } + put(&mut report,0x1d,lux); report[0x2a]=flag; put(&mut report,0x2b,cct); + report[0x2f..0x33].copy_from_slice(&integ.0.to_le_bytes()); report[0x33..0x37].copy_from_slice(&integ.1.to_le_bytes()); + report +} +#[test] fn ct720_color_channels() { + const T:[u32;6]=[5,9,9,9,9,6]; + let data=AopSensorData::new_channels(std::sync::Arc::new(device::Device),T,MsgProc(LUX_OFFSET_CT720)).unwrap(); + let all=|data:&AopSensorData| -> Vec<(i32,i32,i32)> { (0..6).map(|c| read(data,c as u64,T[c])).collect() }; + for channel in 0..6 { assert_eq!(read(&data,channel as u64,T[channel]).0,-61); } + // Red, green, blue, clear in report order; lux and the color temperature as floats. + data.process_fakehid_report(&ct720([100,200,300,400],1,5460.5,(197380,197380),12.5)).unwrap(); + assert_eq!(all(&data),[(2,12,500000),(2,100,0),(2,200,0),(2,300,0),(2,400,0),(2,5460,500000)]); + // Too little light for a color temperature: the counts stay, the temperature reads ENODATA. + data.process_fakehid_report(&ct720([1,2,3,11],1,788.0,(197380,197380),0.5)).unwrap(); + assert_eq!(all(&data),[(2,0,500000),(2,1,0),(2,2,0),(2,3,0),(2,11,0),(-61,-1,-1)]); + data.process_fakehid_report(&ct720([1,2,3,12],1,2904.0,(197380,197380),0.5)).unwrap(); + assert_eq!(read(&data,5,6),(2,2904,0)); + // The firmware's validity byte, and a zero, negative or non-finite temperature. + for (flag,cct) in [(0,5000.0),(1,0.0),(1,-5000.0),(1,f32::NAN),(1,f32::INFINITY)] { + data.process_fakehid_report(&ct720([10,20,30,40],1,4000.0,(197380,197380),1.0)).unwrap(); + assert_eq!(read(&data,5,6),(2,4000,0)); + data.process_fakehid_report(&ct720([10,20,30,40],flag,cct,(197380,197380),1.0)).unwrap(); + assert_eq!(read(&data,5,6).0,-61); assert_eq!(read(&data,4,9),(2,40,0)); + } + // Not the layout the color fields are read from: lux advances, the color sample is withdrawn. + for integ in [(197380,197381),(0,0),(10_000_001,10_000_001)] { + data.process_fakehid_report(&ct720([10,20,30,40],1,4000.0,(197380,197380),1.0)).unwrap(); + data.process_fakehid_report(&ct720([70,80,90,95],1,6000.0,integ,2.0)).unwrap(); + assert_eq!(all(&data),[(2,2,0),(-61,-1,-1),(-61,-1,-1),(-61,-1,-1),(-61,-1,-1),(-61,-1,-1)]); + } + data.process_fakehid_report(&ct720([10,20,30,40],1,4000.0,(10_000_000,10_000_000),1.0)).unwrap(); + assert_eq!(read(&data,1,9),(2,10,0)); + // A short report still carries lux. + data.process_fakehid_report(&ct720([70,80,90,95],1,6000.0,(197380,197380),3.0)[..54]).unwrap(); + assert_eq!(read(&data,0,5),(2,3,0)); assert_eq!(read(&data,1,9).0,-61); + // A report with no lux reading leaves every channel as it was. + data.process_fakehid_report(&ct720([10,20,30,40],1,4000.0,(197380,197380),1.0)).unwrap(); + let before=all(&data); + data.process_fakehid_report(&ct720([70,80,90,95],0,6000.0,(1,2),f32::NAN)).unwrap(); + assert_eq!(all(&data),before); + // A count of u32::MAX saturates the stored reading without touching its neighbours. + data.process_fakehid_report(&ct720([u32::MAX,20,30,40],1,4000.0,(197380,197380),1.0)).unwrap(); + assert_eq!(read(&data,1,9),(2,i32::MAX,999999)); assert_eq!(read(&data,2,9),(2,20,0)); + // The other parts keep their channels: no CT720 field is read at another lux offset. + let report=ct720([100,200,300,400],1,5460.5,(197380,197380),12.5); + for offset in [LUX_OFFSET_VD6286,LUX_OFFSET_CT817] { + for channel in 1..6 { assert_eq!(MsgProc(offset).process_channel(&report,channel),None); assert!(!MsgProc(offset).channel_withdrawn(&report,channel)); } + } +} ''' @@ -130,6 +182,12 @@ def main(): 'cct-zero-valid': ('.filter(|value| *value != 0)', ''), 'channel-alias': ('report_float(message, CCT_OFFSET_VD6286)', 'report_float(message, LUX_OFFSET_VD6286)'), 'missing-saturation': ('value.min(MAX_MICRO)', 'value'), + 'ct720-clear-gate': ('CT720_CCT_MIN_CLEAR: u32 = 12', 'CT720_CCT_MIN_CLEAR: u32 = 1'), + 'ct720-integration-copies': ('integ != 0 && integ == again && ', 'integ != 0 && again != 0 && '), + 'ct720-integration-bound': (' && integ <= CT720_INTEG_MAX', ''), + 'ct720-count-order': ('[0x0d, 0x11, 0x15, 0x19]', '[0x11, 0x0d, 0x15, 0x19]'), + 'ct720-keeps-stale-color': ('self.0 == LUX_OFFSET_CT720 && channel != 0 && self.process(message).is_some()', 'self.0 == LUX_OFFSET_CT720 && channel != 0 && self.process(message).is_none()'), + 'ct720-validity-byte': (' || message.get(CT720_CCT_FLAG).copied() == Some(0)', ''), } with tempfile.TemporaryDirectory(prefix='aop-als-channels-') as directory: directory = Path(directory)