Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
177 changes: 156 additions & 21 deletions drivers/iio/common/aop_sensors/aop_als.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ use kernel::{
device::{self, Bound, Core},
devres,
firmware::Firmware,
iio::common::aop_sensors::{MessageProcessor, MAX_MICRO, MICRO},
iio::common::aop_sensors::{ChannelSpec, MessageProcessor, MAX_MICRO, MICRO},
module_platform_driver, new_delayed_work, new_mutex, new_spinlock, of, platform,
prelude::*,
soc::apple::aop::{EPICService, FakehidListener, FakehidRegistration, AOP},
Expand Down Expand Up @@ -66,7 +66,7 @@ const FIRST_SAMPLE_MS: i64 = 1_000;
const FIRST_SAMPLE_POLL_MS: i64 = 20;
/// How long reports stay on after the last direct read.
const DIRECT_IDLE_MS: i64 = 5_000;
const MAX_CHANNELS: usize = 2;
const MAX_CHANNELS: usize = CT720_CHANS;

const LUX_OFFSET_CT720: usize = 0x1d;
// These offsets address the fake-HID EPIC payload, not a host HID event.
Expand Down Expand Up @@ -765,6 +765,71 @@ fn f32_to_micro(f: u32) -> Option<u64> {
})
}

// FireFish2 / CT720 report, 55 bytes, lux float at +0x1d. The four counts are
// red, green, blue and clear; clear is the wideband channel. 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<u32> {
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<u64> {
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<u64> {
Expand All @@ -784,16 +849,61 @@ 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 {
Light(AlsIioDev),
Color(AlsIioDev),
}

/// 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,
},
]
}

/// A processed channel of type `ty`, as every part has for lux.
fn processed(ty: u32) -> ChannelSpec {
ChannelSpec {
ty,
modifier: None,
info_mask: 1 << bindings::BINDINGS_IIO_CHAN_INFO_PROCESSED,
}
}

impl AlsIio {
fn register(&self) -> Result {
match self {
Expand All @@ -820,6 +930,8 @@ struct State {
control: Arc<Control>,
msg_proc: MsgProc,
ty: [u32; MAX_CHANNELS],
/// Channels that report a raw count rather than a processed value.
raw: [bool; MAX_CHANNELS],
num_channels: usize,
#[pin]
sample: SpinLock<Sample>,
Expand Down Expand Up @@ -923,6 +1035,8 @@ impl FakehidListener for State {
if let Some(value) = *slot {
sample.value[channel] = value;
sample.valid[channel] = true;
} else if self.msg_proc.channel_withdrawn(data, channel) {
sample.valid[channel] = false;
}
}
sample.seen_report = true;
Expand All @@ -948,13 +1062,22 @@ unsafe extern "C" fn als_read_raw(
if channel >= state.num_channels || state.ty[channel] != ty {
return EINVAL.to_errno();
}
if mask != bindings::BINDINGS_IIO_CHAN_INFO_PROCESSED as isize {
let want = match state.raw[channel] {
true => bindings::BINDINGS_IIO_CHAN_INFO_RAW,
false => bindings::BINDINGS_IIO_CHAN_INFO_PROCESSED,
};
if mask != want as isize {
return EINVAL.to_errno();
}
let micro = match state.read_now(channel) {
Ok(value) => value,
Err(e) => return e.to_errno(),
};
if state.raw[channel] {
// SAFETY: The pointer is the caller's result variable.
unsafe { *val = (micro / MICRO) as i32 };
return bindings::IIO_VAL_INT as i32;
}
// Both parts fit an `i32` because stored readings never exceed `MAX_MICRO`.
let (int, frac) = ((micro / MICRO) as i32, (micro % MICRO) as i32);
// SAFETY: The pointers are the caller's result variables.
Expand Down Expand Up @@ -1001,29 +1124,33 @@ impl AlsIioDev {
dev: &device::Device<Bound>,
control: Arc<Control>,
offset: usize,
types: [u32; N],
specs: [ChannelSpec; N],
) -> Result<(Self, Arc<State>)> {
if N == 0 || N > MAX_CHANNELS {
return Err(EINVAL);
}
let info_mask = 1usize << bindings::BINDINGS_IIO_CHAN_INFO_PROCESSED;
let spec = KBox::pin(
Spec::<N> {
channels: core::array::from_fn(|channel| bindings::iio_chan_spec {
type_: types[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 _,
channels: core::array::from_fn(|channel| {
let mut spec = bindings::iio_chan_spec {
type_: specs[channel].ty,
channel2: specs[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: specs[channel].info_mask,
..Default::default()
};
spec.set_modified(specs[channel].modifier.is_some() as _);
spec
}),
info: bindings::iio_info {
read_raw: Some(als_read_raw),
Expand All @@ -1039,12 +1166,17 @@ impl AlsIioDev {
return Err(ENOMEM);
}
let mut ty = [0u32; MAX_CHANNELS];
ty[..N].copy_from_slice(&types);
let mut raw = [false; MAX_CHANNELS];
for (channel, spec) in specs.iter().enumerate() {
ty[channel] = spec.ty;
raw[channel] = spec.info_mask & (1 << bindings::BINDINGS_IIO_CHAN_INFO_RAW) != 0;
}
let state = match Arc::pin_init(
pin_init!(State {
control,
msg_proc: MsgProc(offset),
ty,
raw,
num_channels: N,
sample <- new_spinlock!(Sample::default()),
}),
Expand Down Expand Up @@ -1176,11 +1308,14 @@ impl platform::Driver for IIOAopAlsDriver {
dev,
control.clone(),
offset,
[ty, bindings::BINDINGS_IIO_COLORTEMP],
[processed(ty), processed(bindings::BINDINGS_IIO_COLORTEMP)],
)?;
(AlsIio::Color(iio_dev), state)
} else if offset == LUX_OFFSET_CT720 {
let (iio_dev, state) = AlsIioDev::new(dev, control.clone(), offset, ct720_channels())?;
(AlsIio::Color(iio_dev), state)
} else {
let (iio_dev, state) = AlsIioDev::new(dev, control.clone(), offset, [ty])?;
let (iio_dev, state) = AlsIioDev::new(dev, control.clone(), offset, [processed(ty)])?;
(AlsIio::Light(iio_dev), state)
};
let listener = FakehidRegistration::new(adata, service, state.clone())?;
Expand Down
5 changes: 5 additions & 0 deletions rust/bindings/bindings_helper.h
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
74 changes: 60 additions & 14 deletions rust/kernel/iio/common/aop_sensors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<u32>,
/// 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.
Expand Down Expand Up @@ -104,6 +123,8 @@ impl<T: MessageProcessor, const N: usize> FakehidListener for AopSensorData<T, N
self.value[channel].store(value.min(MAX_MICRO), Relaxed);
// Publishes the reading above to readers that see `valid`.
self.valid[channel].store(true, Release);
} else if self.msg_proc.channel_withdrawn(data, channel) {
self.valid[channel].store(false, Release);
}
}
Ok(())
Expand Down Expand Up @@ -199,26 +220,51 @@ impl<T: MessageProcessor + 'static, const N: usize> IIORegistration<T, N> {
info_mask: usize,
module: &ThisModule,
) -> Result<Self> {
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<AopSensorData<T, N>>,
name: &'static CStr,
channels: [ChannelSpec; N],
module: &ThisModule,
) -> Result<Self> {
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::<T, N>),
Expand Down
Loading
Loading