mirror of https://lore.kernel.org/lkml/
 help / color / mirror / Atom feed
From: Markus Probst <markus.probst@posteo.de>
To: "Lee Jones" <lee@kernel.org>, "Pavel Machek" <pavel@kernel.org>,
	"Griffin Kroah-Hartman" <griffin@kroah.com>,
	"Rob Herring" <robh@kernel.org>,
	"Krzysztof Kozlowski" <krzk+dt@kernel.org>,
	"Conor Dooley" <conor+dt@kernel.org>,
	"Miguel Ojeda" <ojeda@kernel.org>,
	"Boqun Feng" <boqun@kernel.org>, "Gary Guo" <gary@garyguo.net>,
	"Björn Roy Baron" <bjorn3_gh@protonmail.com>,
	"Benno Lossin" <lossin@kernel.org>,
	"Andreas Hindborg" <a.hindborg@kernel.org>,
	"Alice Ryhl" <aliceryhl@google.com>,
	"Trevor Gross" <tmgross@umich.edu>,
	"Danilo Krummrich" <dakr@kernel.org>,
	"Daniel Almeida" <daniel.almeida@collabora.com>,
	"Tamir Duberstein" <tamird@kernel.org>,
	"Alexandre Courbot" <acourbot@nvidia.com>,
	"Onur Özkan" <work@onurozkan.dev>
Cc: linux-leds@vger.kernel.org, devicetree@vger.kernel.org,
	 linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org,
	 driver-core@lists.linux.dev,
	Markus Probst <markus.probst@posteo.de>
Subject: [PATCH v2 4/4] leds: Add driver for disk leds in synology devices
Date: Fri, 04 Dec 2026 12:22:00 +0000	[thread overview]
Message-ID: <20261204-synology_disk_leds-v2-4-12815785ff8b@posteo.de> (raw)
In-Reply-To: <20261204-synology_disk_leds-v2-0-12815785ff8b@posteo.de>

Synology uses an atmega1608 microcontroller as led controller for disk
leds via the I2C bus on its NAS devices. This adds the driver to control
those leds.

Successfully tested on a Synology DS923+.

Signed-off-by: Markus Probst <markus.probst@posteo.de>
---
 MAINTAINERS                        |   7 +
 drivers/leds/Kconfig               |   9 +
 drivers/leds/Makefile              |   1 +
 drivers/leds/leds_synology_disk.rs | 453 +++++++++++++++++++++++++++++++++++++
 4 files changed, 470 insertions(+)

diff --git a/MAINTAINERS b/MAINTAINERS
index d4fc9f48db34..ef1db5f95a37 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -27144,6 +27144,13 @@ F:	drivers/dma-buf/sync_*
 F:	include/linux/sync_file.h
 F:	include/uapi/linux/sync_file.h
 
+SYNOLOGY DISK LED CONTROLLER DRIVER
+M:	Markus Probst <markus.probst@posteo.de>
+L:	linux-leds@vger.kernel.org
+S:	Maintained
+F:	Documentation/devicetree/bindings/leds/synology,disk-leds.yaml
+F:	drivers/leds/leds_synology_disk.rs
+
 SYNOPSYS ARC ARCHITECTURE
 M:	Vineet Gupta <vgupta@kernel.org>
 L:	linux-snps-arc@lists.infradead.org
diff --git a/drivers/leds/Kconfig b/drivers/leds/Kconfig
index 7ec2c8d78542..f8d543971847 100644
--- a/drivers/leds/Kconfig
+++ b/drivers/leds/Kconfig
@@ -332,6 +332,15 @@ config LEDS_WRAP
 	help
 	  This option enables support for the PCEngines WRAP programmable LEDs.
 
+config LEDS_SYNOLOGY_DISK
+	tristate "LED Support for disk leds used in Synology devices"
+	depends on LEDS_CLASS=y && LEDS_CLASS_MULTICOLOR=y
+	depends on I2C=y
+	depends on RUST
+	help
+	  This option enables support for the led controller for disk leds in
+	  synology devices.
+
 config LEDS_COBALT_QUBE
 	tristate "LED Support for the Cobalt Qube series front LED"
 	depends on LEDS_CLASS
diff --git a/drivers/leds/Makefile b/drivers/leds/Makefile
index 4d4b089156e2..0c53186e819a 100644
--- a/drivers/leds/Makefile
+++ b/drivers/leds/Makefile
@@ -91,6 +91,7 @@ obj-$(CONFIG_LEDS_SC27XX_BLTC)		+= leds-sc27xx-bltc.o
 obj-$(CONFIG_LEDS_ST1202)		+= leds-st1202.o
 obj-$(CONFIG_LEDS_SUN50I_A100)		+= leds-sun50i-a100.o
 obj-$(CONFIG_LEDS_SUNFIRE)		+= leds-sunfire.o
+obj-$(CONFIG_LEDS_SYNOLOGY_DISK)	+= leds_synology_disk.o
 obj-$(CONFIG_LEDS_SYSCON)		+= leds-syscon.o
 obj-$(CONFIG_LEDS_TCA6507)		+= leds-tca6507.o
 obj-$(CONFIG_LEDS_TI_LMU_COMMON)	+= leds-ti-lmu-common.o
diff --git a/drivers/leds/leds_synology_disk.rs b/drivers/leds/leds_synology_disk.rs
new file mode 100644
index 000000000000..6ae60bc89cac
--- /dev/null
+++ b/drivers/leds/leds_synology_disk.rs
@@ -0,0 +1,453 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! Led Driver for Synology devices using Atmega1608 as Led Controller.
+//!
+//! Atmega1608 is a microcontroller from Microchip Technology, it is used
+//! as a led controller in synology nas devices for disk leds.
+//!
+//! It can handle a total of 24 leds. Each led has 4 modes:
+//! * OFF - the led is turned off
+//! * ON - the led is turned on at full brightness
+//! * DIM0 - custom brightness and optional hardware accelerated blinking
+//!
+//! there should also be DIM1 (which should do the same as DIM0), but
+//! according to my own testing it doesn't actually work, so it won't be used.
+//!
+//!
+//! # Limitations
+//!
+//! DIM0 (and DIM1) are shared across all leds, meaning if DIM0 is used by
+//! multiple leds, these multiple leds cannot have different brightness
+//! levels. The same does apply for the hardware accelerated blinking.
+//!
+//! In other words, for all 24 leds there can either only be one brightness other
+//! than 0 and 255, or one hardware accelerated blinking delay.
+//!
+//! Furthermore the off and on delay in hardware accelerated blinking cannot
+//! have different values and have to be equal.
+//!
+//! We solve this by only allowing a hardcoded blinking delay of 90 ms.
+//!
+//! While hardware accelerated blinking is on, the led cycles between
+//! the current brightness for the mode and full brightness. Because of this
+//! behaviour, we hardcode the brightness value of 128 for hardware accelerated
+//! blinking.
+//!
+//! Hardware accelerated blinking starts with a delay of 300 - 400 ms.
+//!
+//! # Technical details
+//!
+//! The controller has 6 8-bit i2c registers for led modes. See [`LedAddress`].
+//! Each led has its own 2 bits:
+//!
+//! +=====================================+
+//! | Register  | Leds (2 bits each)      |
+//! +=====================================+
+//! | 0x06      | LED3  LED2  LED1  LED0  |
+//! |-----------+-------------------------+
+//! | 0x07      | LED7  LED6  LED5  LED4  |
+//! |-----------+-------------------------+
+//! | 0x08      | LED11 LED10 LED9  LED8  |
+//! |-----------+-------------------------+
+//! | 0x09      | LED15 LED14 LED13 LED12 |
+//! |-----------+-------------------------+
+//! | 0x0A      | LED19 LED18 LED17 LED16 |
+//! |-----------+-------------------------+
+//! | 0x0B      | LED23 LED22 LED21 LED20 |
+//! |=====================================+
+//!
+//! See [`LedMode`] for the value of each mode.
+//!
+//!
+//! +===============================================+
+//! | Register  | Mode / Meaning                    |
+//! +===============================================+
+//! | 0x01      | turns all leds off if set to 1    |
+//! +-----------------------------------------------+
+//! | 0x02      | blinking delay for Dim0, 1 = 3 ms |
+//! +-----------------------------------------------+
+//! | 0x03      | brightness for Dim0, inverted     |
+//! +-----------------------------------------------+
+//! | 0x04      | blinking delay for Dim1, 1 = 3 ms |
+//! +-----------------------------------------------+
+//! | 0x05      | brightness for Dim1, inverted     |
+//! +===============================================+
+//!
+
+use kernel::{
+    device::{
+        self,
+        Bound,
+        Core, //
+    },
+    i2c::{
+        self,
+        I2cClient,
+        I2cView, //
+    },
+    io::{
+        register::{
+            Array,
+            RegisterArray,
+            RegisterArrayLoc, //
+        },
+        Io,
+        IoLoc,
+        Region, //
+    },
+    led::{
+        self,
+        MultiColorDevice, //
+    },
+    new_mutex,
+    num::Bounded,
+    of,
+    prelude::*,
+    register,
+    sync::{
+        Arc,
+        Mutex, //
+    },
+};
+
+use zerocopy::{
+    try_transmute,
+    ValidityError, //
+};
+use zerocopy_derive::TryFromBytes;
+
+struct SynologyDiskLedDriver<'bound> {
+    client: &'bound I2cClient<Bound>,
+    _leds: KVec<Pin<KBox<MultiColorDevice<'bound, Led<'bound>>>>>,
+}
+
+kernel::module_i2c_driver! {
+    type: SynologyDiskLedDriver<'static>,
+    name: "leds_synology_disk",
+    authors: ["Markus Probst <markus.probst@posteo.de>"],
+    description: "Led Driver for disk leds in synology devices",
+    license: "GPL v2",
+}
+
+const LEDS_PER_ADDR: usize = 4;
+const LED_ADDRESSES: usize = 6;
+const LED_COUNT: usize = LED_ADDRESSES * LEDS_PER_ADDR;
+
+register! {
+    base: Region<256>;
+
+    MASK: bool @ 0x01;
+
+    DIM0_DELAY: u8 @ 0x02;
+    DIM0_BRIGHTNESS: u8 @ 0x03;
+    DIM1_DELAY: u8 @ 0x04;
+    DIM1_BRIGHTNESS: u8 @ 0x05;
+    Modes(u8)[LED_ADDRESSES] @ 0x06 {
+        1:0 led1 ?=> LedMode;
+        3:2 led2 ?=> LedMode;
+        5:4 led3 ?=> LedMode;
+        7:6 led4 ?=> LedMode;
+    }
+}
+
+#[derive(Copy, Clone, PartialEq, Eq, Debug, TryFromBytes)]
+#[repr(u8)]
+enum LedMode {
+    Off = 0,
+    On = 1,
+    Dim0 = 2,
+    #[expect(dead_code)]
+    Dim1 = 3,
+}
+
+impl TryFrom<Bounded<u8, 2>> for LedMode {
+    type Error = ValidityError<u8, Self>;
+
+    fn try_from(value: Bounded<u8, 2>) -> Result<Self, Self::Error> {
+        try_transmute!(*value)
+    }
+}
+
+impl From<LedMode> for Bounded<u8, 2> {
+    fn from(value: LedMode) -> Self {
+        Self::from_expr(value as u8)
+    }
+}
+
+#[pin_data]
+struct LedAddressData {
+    addr: RegisterArrayLoc<Modes>,
+    #[pin]
+    data: Mutex<Modes>,
+}
+
+#[pin_data]
+struct Led<'bound> {
+    client: &'bound I2cClient<Bound>,
+    subleds: KVec<SubLed>,
+    #[pin]
+    blink: Mutex<bool>,
+}
+
+struct SubLed {
+    addr: Arc<LedAddressData>,
+    id: Bounded<u8, 2>,
+}
+
+kernel::of_device_table! {
+    OF_TABLE,
+    <SynologyDiskLedDriver<'_> as i2c::Driver>::IdInfo,
+    [(of::DeviceId::new(c"synology,disk-leds"), ())]
+}
+
+impl i2c::Driver for SynologyDiskLedDriver<'_> {
+    type IdInfo = ();
+    type Data<'bound> = SynologyDiskLedDriver<'bound>;
+
+    const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = Some(&OF_TABLE);
+
+    fn probe<'bound>(
+        idev: &'bound I2cClient<Core<'_>>,
+        _id_info: Option<&'bound Self::IdInfo>,
+    ) -> impl PinInit<Self::Data<'bound>, Error> + 'bound {
+        let dev = idev.as_ref();
+
+        let fwnode = dev.fwnode().ok_or(EINVAL)?;
+
+        let io = idev.smbus_io();
+
+        let addrs = Self::init(&io, dev)?;
+
+        let mut used = [false; LED_COUNT];
+        let mut subleds_classdev = KVec::with_capacity(2, GFP_KERNEL)?;
+        let mut subleds;
+        let mut leds = KVec::new();
+
+        for child in fwnode.children() {
+            subleds_classdev.clear();
+            subleds = KVec::with_capacity(2, GFP_KERNEL)?;
+
+            for (index, color) in child.children().enumerate() {
+                let reg = usize::try_from(color.property_read::<u32>(c"reg").required_by(dev)?)?;
+                if reg >= LED_COUNT {
+                    dev_err!(dev, "{}: property 'reg' is out of bounds\n", *color);
+                    return Err(EINVAL);
+                }
+
+                if used[reg] {
+                    dev_err!(
+                        dev,
+                        "{}: property 'reg' conflicts with a previous entry\n",
+                        *color,
+                    );
+                    return Err(EINVAL);
+                }
+                used[reg] = true;
+
+                let color =
+                    led::Color::try_from(color.property_read::<u32>(c"color").required_by(dev)?)
+                        .map_err(|_err| {
+                            dev_err!(dev, "{}: property 'color' is out of bounds\n", *color);
+                            EINVAL
+                        })?;
+                subleds_classdev.push(
+                    led::MultiColorSubLed::builder(color)
+                        .initial_intensity(if index == 0 { 1 } else { 0 })
+                        .build(),
+                    GFP_KERNEL,
+                )?;
+                subleds.push(
+                    SubLed {
+                        addr: Arc::clone(&addrs[reg / 4]),
+                        id: Bounded::from_expr((reg % 4) as u8),
+                    },
+                    GFP_KERNEL,
+                )?;
+            }
+            debug_assert_eq!(subleds_classdev.len(), subleds.len());
+            if subleds_classdev.is_empty() {
+                dev_err!(dev, "{}: at least one subled is required\n", *child);
+                return Err(EINVAL);
+            }
+
+            leds.push(
+                KBox::pin_init(
+                    led::DeviceBuilder::new()
+                        .fwnode(Some(child))
+                        .build_multicolor(
+                            dev,
+                            try_pin_init!(Led {
+                                client: idev,
+                                subleds,
+                                blink <- new_mutex!(false),
+                            }),
+                            &subleds_classdev,
+                        ),
+                    GFP_KERNEL,
+                )?,
+                GFP_KERNEL,
+            )?;
+        }
+
+        io.try_write(MASK, false)
+            .inspect_err(|err| dev_err!(dev, "Unable to remove led mask: {err:?}\n"))?;
+
+        Ok(SynologyDiskLedDriver {
+            client: idev,
+            _leds: leds,
+        })
+    }
+}
+
+impl SynologyDiskLedDriver<'_> {
+    #[inline]
+    fn init(
+        io: &I2cView<'_, Region<256>>,
+        dev: &device::Device<Bound>,
+    ) -> Result<KVec<Arc<LedAddressData>>> {
+        io.try_write(DIM0_DELAY, 30)
+            .inspect_err(|err| dev_err!(dev, "Unable to set blink delay: {err:?}\n"))?;
+
+        io.try_write(DIM0_BRIGHTNESS, 127)
+            .inspect_err(|err| dev_err!(dev, "Unable to set blink brightness: {err:?}\n"))?;
+
+        let mut addrs = KVec::with_capacity(Modes::SIZE, GFP_KERNEL)?;
+        for index in 0..Modes::SIZE {
+            let addr = Modes::at(index);
+            io.try_write(addr, Modes::zeroed()).inspect_err(|err| {
+                dev_err!(
+                    dev,
+                    "Unable to reset leds at addr {:#2x}: {err:?}\n",
+                    addr.offset()
+                )
+            })?;
+
+            addrs.push_within_capacity(Arc::pin_init(
+                try_pin_init!(LedAddressData {
+                    addr,
+                    data <- new_mutex!(Modes::zeroed()),
+                }),
+                GFP_KERNEL,
+            )?)?;
+        }
+        Ok(addrs)
+    }
+}
+
+impl Drop for SynologyDiskLedDriver<'_> {
+    fn drop(&mut self) {
+        let _ = self
+            .client
+            .smbus_io()
+            .try_write(MASK, true)
+            .inspect_err(|err| dev_err!(self.client.as_ref(), "Unable to set led mask: {err:?}\n"));
+    }
+}
+
+#[vtable]
+impl led::LedOps for Led<'_> {
+    type Mode = led::MultiColor;
+    const BLOCKING: bool = true;
+    const MAX_BRIGHTNESS: u32 = 1;
+
+    fn brightness_set<'bound>(
+        self: &led::MultiColorDevice<'bound, Self>,
+        brightness: u32,
+    ) -> Result<()> {
+        let mut blink = self.blink.lock();
+
+        if brightness == 0 {
+            *blink = false;
+        }
+
+        self.update_modes(|subled_info| {
+            if subled_info.brightness() == 0 {
+                LedMode::Off
+            } else if *blink {
+                LedMode::Dim0
+            } else {
+                LedMode::On
+            }
+        })?;
+
+        Ok(())
+    }
+
+    fn blink_set<'bound>(
+        self: &led::MultiColorDevice<'bound, Self>,
+        delay_on: &mut usize,
+        delay_off: &mut usize,
+    ) -> Result<()> {
+        let mut blink = self.blink.lock();
+        if *delay_on == 0 && *delay_off != 0 {
+            *blink = false;
+            self.update_modes(|_subled_info| LedMode::Off)?;
+            return Ok(());
+        }
+        if *delay_off == 0 && *delay_on != 0 {
+            *blink = false;
+            self.update_modes(|subled_info| {
+                if subled_info.intensity() == 0 {
+                    LedMode::Off
+                } else {
+                    LedMode::On
+                }
+            })?;
+            return Ok(());
+        }
+
+        *delay_on = 90;
+        *delay_off = 90;
+
+        self.update_modes(|subled_info| {
+            if subled_info.intensity() == 0 {
+                LedMode::Off
+            } else {
+                LedMode::Dim0
+            }
+        })?;
+        *blink = true;
+
+        Ok(())
+    }
+}
+
+impl Led<'_> {
+    fn update_modes<F: FnMut(&led::MultiColorSubLed) -> LedMode>(
+        self: &led::MultiColorDevice<'_, Self>,
+        mut func: F,
+    ) -> Result<()> {
+        let mut guards = core::array::from_fn::<_, LED_ADDRESSES, _>(|_| None);
+
+        for (subled, subled_info) in self.subleds.iter().zip(self.subleds()) {
+            let (_, goal, _) = guards[subled.addr.addr.index()].get_or_insert_with(|| {
+                let guard = subled.addr.data.lock();
+                (subled.addr.addr, *guard, guard)
+            });
+            let mode = (func)(subled_info);
+
+            *goal = match *subled.id {
+                0 => goal.with_led1(mode),
+                1 => goal.with_led2(mode),
+                2 => goal.with_led3(mode),
+                3 => goal.with_led4(mode),
+                _ => unreachable!(),
+            };
+        }
+
+        let io = self.client.smbus_io();
+        for (addr, goal, mut current) in guards.into_iter().flatten() {
+            if goal != *current {
+                io.try_write(addr, goal).inspect_err(|err| {
+                    dev_err!(
+                        self.client.as_ref(),
+                        "failed to write {:#2x}: {err:?}\n",
+                        addr.offset()
+                    );
+                })?;
+                *current = goal;
+            }
+        }
+        Ok(())
+    }
+}

-- 
2.56.1


      parent reply	other threads:[~2026-12-04 12:22 UTC|newest]

Thread overview: 7+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2026-12-04 12:21 [PATCH v2 0/4] " Markus Probst
2026-12-04 12:21 ` [PATCH v2 1/4] dt-bindings: leds: Add synology disk led controller Markus Probst
2026-12-04 12:21 ` [PATCH v2 2/4] rust: io: Add `RegisterArrayLoc::index` Markus Probst
2026-12-04 12:21 ` [PATCH v2 3/4] rust: io: Implement Copy for RegisterArrayLoc Markus Probst
2026-12-04 13:38   ` Gary Guo
2026-12-04 13:42     ` Markus Probst
2026-12-04 12:22 ` Markus Probst [this message]

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=20261204-synology_disk_leds-v2-4-12815785ff8b@posteo.de \
    --to=markus.probst@posteo.de \
    --cc=a.hindborg@kernel.org \
    --cc=acourbot@nvidia.com \
    --cc=aliceryhl@google.com \
    --cc=bjorn3_gh@protonmail.com \
    --cc=boqun@kernel.org \
    --cc=conor+dt@kernel.org \
    --cc=dakr@kernel.org \
    --cc=daniel.almeida@collabora.com \
    --cc=devicetree@vger.kernel.org \
    --cc=driver-core@lists.linux.dev \
    --cc=gary@garyguo.net \
    --cc=griffin@kroah.com \
    --cc=krzk+dt@kernel.org \
    --cc=lee@kernel.org \
    --cc=linux-kernel@vger.kernel.org \
    --cc=linux-leds@vger.kernel.org \
    --cc=lossin@kernel.org \
    --cc=ojeda@kernel.org \
    --cc=pavel@kernel.org \
    --cc=robh@kernel.org \
    --cc=rust-for-linux@vger.kernel.org \
    --cc=tamird@kernel.org \
    --cc=tmgross@umich.edu \
    --cc=work@onurozkan.dev \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox

all inboxes | Powered by JetHome®