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,
	 Markus Probst <markus.probst@posteo.de>
Subject: [PATCH 2/2] leds: add driver for disk leds in synology devices
Date: Wed, 02 Dec 2026 15:21:19 +0000	[thread overview]
Message-ID: <20261202-synology_disk_leds-v1-2-53249fd3a2ad@posteo.de> (raw)
In-Reply-To: <20261202-synology_disk_leds-v1-0-53249fd3a2ad@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 | 441 +++++++++++++++++++++++++++++++++++++
 4 files changed, 458 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..34cf2a3f0bac 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 && LEDS_CLASS_MULTICOLOR
+	depends on I2C
+	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..466549f65f9c 100644
--- a/drivers/leds/Makefile
+++ b/drivers/leds/Makefile
@@ -101,6 +101,7 @@ obj-$(CONFIG_LEDS_UPBOARD)		+= leds-upboard.o
 obj-$(CONFIG_LEDS_WM831X_STATUS)	+= leds-wm831x-status.o
 obj-$(CONFIG_LEDS_WM8350)		+= leds-wm8350.o
 obj-$(CONFIG_LEDS_WRAP)			+= leds-wrap.o
+obj-$(CONFIG_LEDS_SYNOLOGY_DISK)	+= leds_synology_disk.o
 
 # Kinetic ExpressWire Protocol
 obj-$(CONFIG_LEDS_EXPRESSWIRE)		+= leds-expresswire.o
diff --git a/drivers/leds/leds_synology_disk.rs b/drivers/leds/leds_synology_disk.rs
new file mode 100644
index 000000000000..1f339e2e429e
--- /dev/null
+++ b/drivers/leds/leds_synology_disk.rs
@@ -0,0 +1,441 @@
+// 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::{
+        Bound,
+        Core, //
+    },
+    i2c::{
+        self,
+        I2cClient, //
+    },
+    io::Io,
+    led::{self, MultiColorDevice},
+    new_mutex, of,
+    prelude::*,
+    sync::{
+        Arc,
+        Mutex, //
+    },
+};
+
+struct SynologyDiskLedDriver<'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",
+}
+
+#[repr(u8)]
+#[derive(Copy, Clone, PartialEq, Eq)]
+enum LedAddress {
+    Ls0 = 0x06,
+    Ls1 = 0x07,
+    Ls2 = 0x08,
+    Ls3 = 0x09,
+    Ls4 = 0x0A,
+    Ls5 = 0x0B,
+}
+
+#[repr(u8)]
+#[derive(Copy, Clone)]
+enum LedId {
+    Sel0 = 0,
+    Sel1 = 1,
+    Sel2 = 2,
+    Sel3 = 3,
+}
+
+#[repr(u8)]
+#[derive(Copy, Clone, PartialEq, Eq, Debug)]
+enum LedMode {
+    Off = 0b00,
+    On = 0b01,
+    Dim0 = 0b10,
+    // Dim1 = 0b11,
+}
+
+#[pin_data]
+struct LedAddressData {
+    addr: LedAddress,
+    #[pin]
+    data: Mutex<u8>,
+}
+
+#[pin_data]
+struct Led<'bound> {
+    client: &'bound I2cClient<Bound>,
+    addr: Arc<Pin<KBox<[LedAddressData]>>>,
+    subleds: KVec<SubLed>,
+    #[pin]
+    blink: Mutex<bool>,
+}
+
+struct SubLed {
+    addr: LedAddress,
+    id: LedId,
+}
+
+kernel::of_device_table! {
+    OF_TABLE,
+    <SynologyDiskLedDriver<'_> as i2c::Driver>::IdInfo,
+    [(of::DeviceId::new(c"synology,disk-leds"), 0)]
+}
+
+impl i2c::Driver for SynologyDiskLedDriver<'_> {
+    type IdInfo = u32;
+    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 Some(fwnode) = dev.fwnode() else {
+            return Err(EINVAL);
+        };
+
+        idev.smbus_io()
+            .try_write8(30, 0x02)
+            .inspect_err(|err| dev_err!(dev, "unable to set blink delay: {err:?}\n"))?;
+
+        idev.smbus_io()
+            .try_write8(127, 0x03)
+            .inspect_err(|err| dev_err!(dev, "unable to set blink brightness: {err:?}\n"))?;
+
+        let addr = Arc::new(
+            KBox::pin_slice::<_, _, Error, Error>(
+                |index| {
+                    try_pin_init!(LedAddressData {
+                        addr: LedAddress::VALUES[index],
+                        data <- new_mutex!(0u8),
+                    })
+                },
+                LedAddress::VALUES.len(),
+                GFP_KERNEL,
+            )?,
+            GFP_KERNEL,
+        )?;
+        let mut used = [false; LedId::VALUES.len() * LedAddress::VALUES.len()];
+        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 >= LedAddress::VALUES.len() * LedId::VALUES.len() {
+                    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::new(color).initial_intensity(if index == 0 {
+                        1
+                    } else {
+                        0
+                    }),
+                    GFP_KERNEL,
+                )?;
+                subleds.push(
+                    SubLed {
+                        addr: LedAddress::VALUES[reg / LedId::VALUES.len()],
+                        id: LedId::VALUES[reg % LedId::VALUES.len()],
+                    },
+                    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);
+            }
+
+            let addr = Arc::clone(&addr);
+            leds.push(
+                KBox::pin_init(
+                    led::DeviceBuilder::new()
+                        .fwnode(Some(child))
+                        .build_multicolor(
+                            dev,
+                            try_pin_init!(Led {
+                                client: idev,
+                                subleds,
+                                addr,
+                                blink <- new_mutex!(false),
+                            }),
+                            &subleds_classdev,
+                        ),
+                    GFP_KERNEL,
+                )?,
+                GFP_KERNEL,
+            )?;
+        }
+
+        idev.smbus_io()
+            .try_write8(0, 0x01)
+            .inspect_err(|err| dev_err!(dev, "unable to remove led mask: {err:?}\n"))?;
+
+        Ok(SynologyDiskLedDriver { _leds: leds })
+    }
+
+    fn unbind<'bound>(dev: &'bound I2cClient<Core<'_>>, _this: Pin<&Self::Data<'bound>>) {
+        let _ = dev
+            .smbus_io()
+            .try_write8(1, 0x01)
+            .inspect_err(|err| dev_err!(dev.as_ref(), "unable to set led mask: {err:?}\n"));
+
+        for addr in LedAddress::VALUES {
+            let _ = dev
+                .smbus_io()
+                .try_write8(0, addr as usize)
+                .inspect_err(|err| {
+                    dev_err!(
+                        dev.as_ref(),
+                        "Unable to turn off leds at address {:#2x}: {err:?}\n",
+                        (addr as u8)
+                    )
+                });
+        }
+    }
+}
+
+impl LedAddress {
+    const VALUES: [Self; 6] = [
+        Self::Ls0,
+        Self::Ls1,
+        Self::Ls2,
+        Self::Ls3,
+        Self::Ls4,
+        Self::Ls5,
+    ];
+}
+
+impl LedId {
+    const VALUES: [Self; 4] = [Self::Sel0, Self::Sel1, Self::Sel2, Self::Sel3];
+
+    const fn mask(self) -> u8 {
+        match self {
+            Self::Sel0 => 0x03,
+            Self::Sel1 => 0x0C,
+            Self::Sel2 => 0x30,
+            Self::Sel3 => 0xC0,
+        }
+    }
+
+    const fn shift(self) -> u8 {
+        match self {
+            Self::Sel0 => 0,
+            Self::Sel1 => 2,
+            Self::Sel2 => 4,
+            Self::Sel3 => 6,
+        }
+    }
+}
+
+#[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<()> {
+        for LedAddressData { addr, data } in &**self.addr {
+            let mut guard = None;
+            for (subled, subled_info) in self.subleds.iter().zip(self.subleds()) {
+                if subled.addr == *addr {
+                    let (goal, _) = guard.get_or_insert_with(|| {
+                        let guard = data.lock();
+                        (*guard, guard)
+                    });
+                    let mode = (func)(subled_info);
+                    *goal = (*goal & !subled.id.mask())
+                        | (((mode as u8) << subled.id.shift()) & subled.id.mask());
+                }
+            }
+            if let Some((goal, mut current)) = guard {
+                if goal != *current {
+                    self.client
+                        .smbus_io()
+                        .try_write8(goal, *addr as usize)
+                        .inspect_err(|err| {
+                            dev_err!(
+                                self.client.as_ref(),
+                                "failed to write {:#2x}: {err:?}\n",
+                                (*addr as u8)
+                            );
+                        })?;
+                    *current = goal;
+                }
+            }
+        }
+        Ok(())
+    }
+}

-- 
2.56.1


      parent reply	other threads:[~2026-12-02 15:21 UTC|newest]

Thread overview: 3+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2026-12-02 15:21 [PATCH 0/2] " Markus Probst
2026-12-02 15:21 ` [PATCH 1/2] dt-bindings: leds: Add synology disk led controller Markus Probst
2026-12-02 15:21 ` 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=20261202-synology_disk_leds-v1-2-53249fd3a2ad@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=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®