From mboxrd@z Thu Jan 1 00:00:00 1970 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=209.85.216.42 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1796144140; b=h5SRx7Q82AyrYWWAFH4l8334031V+Se2Zu7LzvXSDaMMfbVIFTn2lTSOD3dYKOUfyxPI pmjIF1uFq2AQEQDcDaoyok9xrEx+43VcYGsbjfDnrnf2wPGFzlqRus0wyRFO8+4m7/DaG Yg7yE45X4xjqutIaW4Hd5+gLnOsJo4pru5WUkqdSTXZE+9U33hXR8bj2TNluiOEmFwIaV oAon/Lc5zuoA+HrvtzRoFsAw4ZMJSz9BMlIhZeM2LPubi9qtxFBJwx+8HK0iHJHqZ2C22 sc7psqCT5InBK5UI4HjWue4zGSsUn6LLjiXHwqyAmod0s2Pk6b07qHVgqY2jOD4/D9A== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1796144140; h=DMARC-Filter:Received:DKIM-Signature:X-Google-DKIM-Signature: X-Forwarded-Encrypted:X-Gm-Message-State:X-Gm-Gg:X-Received:Received: From:To:Cc:Subject:Date:Message-ID:X-Mailer:In-Reply-To:References: MIME-Version:Content-Transfer-Encoding; bh=7nk6xFFJZZkm/qpdH1MS12+N/NSsAnXA4IP/u/WOk04=; b=M4WRZvgyVYbUHsC12YlF+VBdTlJEr0UK4AQ060MLc5OX9HMpuKmjn31GJEleZJWPxnhJ wA8c5ZU/QxHYxhmwkUMYeUY1fokI/IEaYUd46xtgZS6XQ13FBGuA4KOKdLiB0mFi+xAX0 NEJULVKVqCzlt7BS4HmN/ZHLIy4T+P0ZsQvIuDCc8lZaIEJpgdByiuwcJ4EDcWmNZYEYw DBKNqJn4qf5HdT7puJbCb4cArxSh4DykB6C7+eq/vv7VwNLfXcGvxB0b23uMZ2t9odwpH J65vJeZolCgK92phM0ytn/DJFfpb9pU9Dlb344PJbdgXgmWYdbNZoKrDcthX0wnVAyw== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=gmail.com; spf=pass smtp.mailfrom=gmail.com; dkim=pass header.d=gmail.com header.i=@gmail.com header.a=rsa-sha256 header.s=20260707 header.b=Bgbc6yPW; arc=none smtp.remote-ip=209.85.216.42 Received: from mail-pj1-f42.google.com (mail-pj1-f42.google.com [209.85.216.42]) (using TLSv1.3 with cipher TLS_AES_128_GCM_SHA256 (128/128 bits) key-exchange X25519 server-signature ECDSA (prime256v1) server-digest SHA256) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 63EC660A2604 for ; Tue, 1 Dec 2026 16:55:40 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org 63EC660A2604 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=gmail.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=gmail.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.a=rsa-sha256 header.s=20260707 header.b=Bgbc6yPW Received: by mail-pj1-f42.google.com with SMTP id 98e67ed59e1d1-3b3a42a4bcdso4910523a91.0 for ; Tue, 01 Dec 2026 08:55:40 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20260707; t=1796144139; x=1796748939; darn=vger.kernel.org; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:from:to:cc:subject:date :message-id:reply-to:content-type; bh=7nk6xFFJZZkm/qpdH1MS12+N/NSsAnXA4IP/u/WOk04=; b=Bgbc6yPW7S8cTe6y6QBcQ22Fn0y0K7+5sLa6S4OvlOpQWeqRkTJW4+HjmmvOsqyNAM pV6oRWYnK/ivOyn/Y96qHMz7b+V3sODF7K351Wgl1lLLWgn3+aCOhnkxeYNePwmmBxqX s7RKXL7Vya5CohrVSiwOo5739Vvk4Pqnntap4GZAjR/eqvjd7E8dH3U39Oa9tCbH2SY6 IutASlxshJP9JENLJ+4KQKkNoQLKqP29y6zIewmfZeH/3CRRhoNQfwT4oClt/1TRcIDk b7NO5Diyd6lQuaWYefuta+ajtrrkjvhEpv7JNMs16P2aEftDcXqlvwP0uiVSTi2dbh2G A4DQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20260707; t=1796144139; x=1796748939; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-gg:x-gm-message-state:from :to:cc:subject:date:message-id:reply-to:content-type; bh=7nk6xFFJZZkm/qpdH1MS12+N/NSsAnXA4IP/u/WOk04=; b=Ndtwg/v4wp47k4S4IL5JlKPNCiaVmQwIsBxb0NoZ5eJ3xErq5kIQs/VP6BDirDN6zB csqDNHOG9qbSKufu1JfDdd13jdHyBeN5HiJS9+AJxOsz3hKh77BITUS4V5RsGQSeVeQA CkRiiCkPApTaN643FVjdxOHp316cTNcTHtFvGJ0cFuRCcXWWjSCW0C6nat5QsHDBpL9C Qrm/VKzfGUK2b/pi7zGJRYl35f4SU/R7Zb3VVrPO6UAfIZOI8X5O4c/w3QNAPcmJJ/Ki Bq3Ova1+dQ+IEA98J6xvy+n70bDQIvUFofA6JTyZ6E0BkT9+rygNnlWlV4GyHFn4QiSP ecDQ== X-Forwarded-Encrypted: i=1; AL+hErGBaHS6d69tZ+6IRxnizxcXUNyu6nZyQYdlSGvGeqws3SmjHp1k8uGlHZugF+WU9aXTa/xV9E7cwMi5efRPng==@vger.kernel.org X-Gm-Message-State: APuU4Z87x89ClBhggDZVd4xZSorPf4Q1db/CXxoWtEhWU0ddSsTPScJw k3MfcZkmts43I8HnEyM6W3Z8GcWx2CzadpLv1AGIqNlMMcNl5Omuyt8i X-Gm-Gg: AZFdTZdalldrquDa8odDcy5CydDODWH6Pt+DZuSlk+BR61eXICrrR3Q1qN06zCPTkx2 4l2dct//BEZa/DpfF9CxZ8zIPN+9FU3phw9aZUvr0p5MhShzCHlqC4PTUBVa9mD+MgW+sQLnu6v yzEKPn99nqGTfW6F0hidFhsULm/sEQrLpugGvRaKmB8gMYihXE2jxXOU+az8RFe5/zK0loPOB34 kcb45DORIEZmGQ2juxyxTVfJc5khGCGwzAPco1jzrqWMaiNZJJNPpb8s9Ry4+BZBloLQeinBCDg W3oNkjt4+OKWbVXB2TM/SaxoMAr7jr8BN5xWrfjkqjPE/B+PHOOrTdo7Wls911gDDShS2662Nml F9+kaASoQ6FKtG9SZEotZhiL9r7XzNta+kGadSt1txDSG35G2Ah8ppqJ9c6kYhpKxxjppibx7gf LqF7ca2a9zx/lpLTSq/KdbzsnX9WkS+WhbZZDJLZfh0Xq/4wqbMW0oGYlv5EyueglHK9gk7aU9N /94bfm2KzWfotAfajPljxHCc/rnVHvdPb73G25zMz81R3qpGt6I6jEKjT7w/UeLn1/19OOc9inj 95SnziJkPZdMwlFrS2PTUh/LBOFpltp+jsNiXR6Iz5Pz2nP+VXTzcDFaReHmLQHBFXi1 X-Received: by 2002:a17:90b:3e8a:b0:3b5:8d10:28b2 with SMTP id 98e67ed59e1d1-3b58d102a71mr5541126a91.44.1796144139376; Tue, 01 Dec 2026 08:55:39 -0800 (PST) Received: from localhost.localdomain ([36.68.98.203]) by smtp.gmail.com with ESMTPSA id 98e67ed59e1d1-3b44b73b2b3sm29159174a91.2.2026.12.01.08.55.34 (version=TLS1_3 cipher=TLS_CHACHA20_POLY1305_SHA256 bits=256/256); Tue, 01 Dec 2026 08:55:38 -0800 (PST) From: Muchamad Coirul Anwar To: Jonathan Cameron , Miguel Ojeda , Igor Korotin , Danilo Krummrich Cc: David Lechner , =?UTF-8?q?Nuno=20S=C3=A1?= , Andy Shevchenko , Andi Shyti , Daniel Almeida , Alice Ryhl , Mark Brown , Joshua Crofts , Markus Probst , Shuai Liu <847807867@qq.com>, linux-iio@vger.kernel.org, linux-i2c@vger.kernel.org, rust-for-linux@vger.kernel.org, driver-core@lists.linux.dev, linux-kernel@vger.kernel.org Subject: [RFC PATCH v8 4/4] iio: position: add Rust driver for ams AS5600 Date: Tue, 1 Dec 2026 23:55:08 +0700 Message-ID: <20261201165508.39336-5-muchamadcoirulanwar@gmail.com> X-Mailer: git-send-email 2.50.0 In-Reply-To: <20261201165508.39336-1-muchamadcoirulanwar@gmail.com> References: <20261201165508.39336-1-muchamadcoirulanwar@gmail.com> X-Mailing-List: rust-for-linux@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list MIME-Version: 1.0 Content-Transfer-Encoding: 8bit Add a Rust driver for the ams AS5600 12-bit magnetic rotary position sensor. Expose the raw angle and scale through the IIO sysfs interface in direct mode. Read the status register before each angle sample and return ENODATA when the magnet-detected bit is clear. Serialize the status and angle transaction sequence with a mutex and propagate I2C transport errors directly to userspace. Capture a bound I2C client reference during probe and store it in the IIO private data. The registered IIO device carries the same bound lifetime, keeping the client valid throughout read_raw callbacks. The AS5600 stores the raw angle with the high byte at register 0x0c. Use the byte-swapped SMBus word helper and mask the result to 12 bits. Add usize bit and mask helpers for constructing the IIO channel information mask. Suggested-by: Shuai Liu <847807867@qq.com> Link: https://lore.kernel.org/all/tencent_173B7731E90B9624F9F82613DC3031B70907@qq.com/ Link: https://lore.kernel.org/all/179286358623.55649.5397316745104390556@linux.dev/ Co-developed-by: Igor Korotin Signed-off-by: Igor Korotin Signed-off-by: Muchamad Coirul Anwar --- drivers/iio/position/Kconfig | 11 ++ drivers/iio/position/Makefile | 1 + drivers/iio/position/as5600.rs | 193 +++++++++++++++++++++++++++++++++ rust/kernel/bits.rs | 29 +++++ 4 files changed, 234 insertions(+) create mode 100644 drivers/iio/position/as5600.rs diff --git a/drivers/iio/position/Kconfig b/drivers/iio/position/Kconfig index 1576a6380b53..7c278f82f53d 100644 --- a/drivers/iio/position/Kconfig +++ b/drivers/iio/position/Kconfig @@ -6,6 +6,17 @@ menu "Linear and angular position sensors" +config AS5600 + tristate "ams AS5600 magnetic rotary position sensor" + depends on IIO=y && I2C=y && RUST + help + Support for the ams OSRAM AS5600 12-bit magnetic rotary + position sensor. Provides in_angl_raw (0-4095) and + in_angl_scale (radians per LSB) via sysfs. + + To compile this driver as a module, choose M here: the + module will be called as5600. + config IQS624_POS tristate "Azoteq IQS624/625 angular position sensors" depends on MFD_IQS62X || COMPILE_TEST diff --git a/drivers/iio/position/Makefile b/drivers/iio/position/Makefile index d70902f2979d..2d26f6d6ace3 100644 --- a/drivers/iio/position/Makefile +++ b/drivers/iio/position/Makefile @@ -4,5 +4,6 @@ # When adding new entries keep the list in alphabetical order +obj-$(CONFIG_AS5600) += as5600.o obj-$(CONFIG_HID_SENSOR_CUSTOM_INTEL_HINGE) += hid-sensor-custom-intel-hinge.o obj-$(CONFIG_IQS624_POS) += iqs624-pos.o diff --git a/drivers/iio/position/as5600.rs b/drivers/iio/position/as5600.rs new file mode 100644 index 000000000000..26a9d5bb7395 --- /dev/null +++ b/drivers/iio/position/as5600.rs @@ -0,0 +1,193 @@ +// SPDX-License-Identifier: GPL-2.0-only +// Copyright (C) 2026 Muchamad Coirul Anwar +//! Driver for ams AS5600 12-bit magnetic rotary position sensor. +//! +//! Exposes `in_angl_raw` and `in_angl_scale` through the IIO sysfs interface +//! in `INDIO_DIRECT_MODE`. +//! +//! Datasheet: AS5600, document DS000365. + +use kernel::{ + bindings::{ + iio_chan_info_enum_IIO_CHAN_INFO_RAW, + iio_chan_info_enum_IIO_CHAN_INFO_SCALE, + iio_chan_spec, + iio_chan_type_IIO_ANGL, + INDIO_DIRECT_MODE, // + }, + bits::{ + bit_u8, + bit_usize, + genmask_u16, // + }, + device::{ + Bound, + Core, // + }, + error::code::ENODATA, + i2c::{ + DeviceId, + Driver, + I2cClient, + IdTable, // + }, + i2c_device_table, + iio::{ + Device, + IioChanInfo, + IioDriver, + IioVal, + Registered, // + }, + io::Io, + module_i2c_driver, + of, + of_device_table, + prelude::*, + sync::{ + new_mutex, + Mutex, // + }, // +}; + +const AS5600_REG_STATUS: u8 = 0x0B; +const AS5600_REG_RAW_ANGLE_H: u8 = 0x0C; + +const AS5600_STATUS_MD: u8 = bit_u8(5); +const AS5600_RAW_ANGLE_MASK: u16 = genmask_u16(0..=11); + +module_i2c_driver! { + type: As5600, + name: "as5600", + authors: ["Muchamad Coirul Anwar"], + description: "I2C Driver for ams OSRAM AS5600 Magnetic Rotary Position Sensor", + license: "GPL", +} + +i2c_device_table!( + I2C_TABLE, + ::IdInfo, + [(DeviceId::new(c"as5600"), ())] +); + +of_device_table!( + OF_TABLE, + ::IdInfo, + [(of::DeviceId::new(c"ams,as5600"), ())] +); + +struct As5600Channels([iio_chan_spec; 1]); + +// SAFETY: `iio_chan_spec` is a plain C struct with no interior mutability. +// All pointer fields (`event_spec`, `ext_info`, `extend_name`, etc.) are +// NULL - set via `zeroed()` and never reassigned - so no shared mutable +// state exists behind them. The static is a compile-time constant with no +// `&mut` access path, making concurrent shared access safe. +unsafe impl Sync for As5600Channels {} + +static AS5600_CHANNELS: As5600Channels = As5600Channels({ + // SAFETY: `iio_chan_spec` is a repr(C) struct where all-zeroes is valid + // (integers default to 0, pointers to NULL). + let mut chan: iio_chan_spec = unsafe { core::mem::zeroed() }; + chan.type_ = iio_chan_type_IIO_ANGL; + chan.info_mask_separate = bit_usize(iio_chan_info_enum_IIO_CHAN_INFO_RAW) + | bit_usize(iio_chan_info_enum_IIO_CHAN_INFO_SCALE); + [chan] +}); + +#[pin_data] +struct As5600Priv<'a> { + client: &'a I2cClient, + #[pin] + io_lock: Mutex<()>, +} + +// SAFETY: AS5600_CHANNELS contains one valid, immutable IIO_ANGL channel +// exposing only RAW and SCALE. It has no event or extension callbacks, +// and all optional pointer fields are null. +unsafe impl IioDriver for As5600Priv<'_> { + fn read_raw(&self, _chan: *const iio_chan_spec, info: IioChanInfo) -> Result { + match info { + IioChanInfo::Raw => { + let _guard = self.io_lock.lock(); + let client = self.client; + + let io = client.smbus_io(); + // Read status register to verify magnet presence before + // reading the angle. + let status = io.try_read8(usize::from(AS5600_REG_STATUS))?; + + if (status & AS5600_STATUS_MD) == 0 { + return Err(ENODATA); + } + + // Word read at register 0x0C returns big-endian data. + // smbus_read_word_swapped() handles the byte swap. + let raw = client.smbus_read_word_swapped(AS5600_REG_RAW_ANGLE_H)?; + let angle = raw & AS5600_RAW_ANGLE_MASK; + Ok(IioVal::Int(i32::from(angle))) + } + // Scale factor: radians per LSB = 2*pi / 4096 ~= 0.001533981 + IioChanInfo::Scale => Ok(IioVal::IntPlusNano(0, 1533981)), + } + } + + fn channels(&self) -> &'static [iio_chan_spec] { + &AS5600_CHANNELS.0 + } +} + +struct As5600; + +#[pin_data] +struct As5600Data<'bound> { + _iio_dev: Device<'bound, As5600Priv<'bound>, Registered>, +} + +impl Driver for As5600 { + type IdInfo = (); + type Data<'bound> = As5600Data<'bound>; + + const I2C_ID_TABLE: Option> = Some(&I2C_TABLE); + const OF_ID_TABLE: Option> = Some(&OF_TABLE); + + // `try_pin_init!` returns a concrete anonymous type that may expose more + // bounds than the trait signature declares (e.g. auto-traits like `Send`). + // This refinement of the RPITIT return type is intentional. + #[allow(refining_impl_trait)] + fn probe<'bound>( + dev: &'bound I2cClient>, + _id_info: Option<&'bound Self::IdInfo>, + ) -> impl PinInit, Error> + 'bound { + try_pin_init!(As5600Data { + _iio_dev: { + // Deref coercion: I2cClient> -> I2cClient. + let client: &'bound I2cClient = dev; + + let priv_init = pin_init!(As5600Priv { + client, + io_lock <- new_mutex!(()), + }); + + let unregistered = + Device::build_device(dev.as_ref(), c"as5600", INDIO_DIRECT_MODE, priv_init)?; + + // SAFETY: + // - The returned `Device` is stored directly inside `As5600Data<'bound>`, + // which `i2c::Adapter` owns via `set_drvdata()` and drops in + // `post_unbind_rust` (both on unbind and on post-probe failure in + // `really_probe()`); it is never leaked or exposed to safe callers. + // - Dropping `As5600Data<'bound>` runs `iio_device_unregister()` before + // destroying `As5600Priv<'bound>` and before `'bound` ends (`dev->driver` + // and `i2c_client` remain valid until after `post_unbind_rust`). + // - `LocalModule` is this module (`as5600`), which defines `As5600Priv`, + // `AS5600_CHANNELS`, and `c"as5600"`; `module_i2c_driver!` unregisters + // the I2C driver (unbinding all devices) before module unload. + // - Nothing else holds a raw pointer to unregister or free this `iio_dev`. + unsafe { + unregistered.register(kernel::module::this_module::())? + } + } + }) + } +} diff --git a/rust/kernel/bits.rs b/rust/kernel/bits.rs index 2daead125626..a6537a668dd6 100644 --- a/rust/kernel/bits.rs +++ b/rust/kernel/bits.rs @@ -41,6 +41,7 @@ pub const fn [](n: u32) -> $ty { impl_bit_fn!(u32); impl_bit_fn!(u16); impl_bit_fn!(u8); +impl_bit_fn!(usize); macro_rules! impl_genmask_fn { ( @@ -203,3 +204,31 @@ pub const fn [](range: RangeInclusive) -> $ty { /// assert_eq!(genmask_u8(0..=7), u8::MAX); /// ``` ); + +impl_genmask_fn!( + usize, + /// # Examples + /// + /// ``` + /// # #![expect(clippy::reversed_empty_ranges)] + /// # use kernel::bits::genmask_checked_usize; + /// assert_eq!(genmask_checked_usize(0..=0), Some(0b1)); + /// assert_eq!(genmask_checked_usize(0..=3), Some(0b1111)); + /// assert_eq!(genmask_checked_usize(1..=3), Some(0b1110)); + /// + /// // `200` is out of the supported bit range on all platforms. + /// assert_eq!(genmask_checked_usize(0..=200), None); + /// + /// // Invalid range where the start is bigger than the end. + /// assert_eq!(genmask_checked_usize(5..=2), None); + /// ``` + , + /// # Examples + /// + /// ``` + /// # use kernel::bits::genmask_usize; + /// assert_eq!(genmask_usize(0..=0), 0b1); + /// assert_eq!(genmask_usize(0..=3), 0b1111); + /// assert_eq!(genmask_usize(1..=3), 0b1110); + /// ``` +); -- 2.50.0