LED handling under Linux

In its simplest form, the LED class just allows control of LEDs fromuserspace. LEDs appear in /sys/class/leds/. The maximum brightness of theLED is defined in max_brightness file. The brightness file will set the brightnessof the LED (taking a value 0-max_brightness). Most LEDs don’t have hardwarebrightness support so will just be turned on for non-zero brightness settings.

The class also introduces the optional concept of an LED trigger. A triggeris a kernel based source of led events. Triggers can either be simple orcomplex. A simple trigger isn’t configurable and is designed to slot intoexisting subsystems with minimal additional code. Examples are the disk-activity,nand-disk and sharpsl-charge triggers. With led triggers disabled, the codeoptimises away.

Complex triggers while available to all LEDs have LED specificparameters and work on a per LED basis. The timer trigger is an example.The timer trigger will periodically change the LED brightness betweenLED_OFF and the current brightness setting. The “on” and “off” time canbe specified via /sys/class/leds/<device>/delay_{on,off} in milliseconds.You can change the brightness value of a LED independently of the timertrigger. However, if you set the brightness value to LED_OFF it willalso disable the timer trigger.

You can change triggers in a similar manner to the way an IO scheduleris chosen (via /sys/class/leds/<device>/trigger). Trigger specificparameters can appear in /sys/class/leds/<device> once a given trigger isselected.

Design Philosophy

The underlying design philosophy is simplicity. LEDs are simple devicesand the aim is to keep a small amount of code giving as much functionalityas possible. Please keep this in mind when suggesting enhancements.

LED Device Naming

Is currently of the form:

“devicename:color:function”

  • devicename:

    it should refer to a unique identifier created by the kernel,like e.g. phyN for network devices or inputN for input devices, ratherthan to the hardware; the information related to the product and the busto which given device is hooked is available in sysfs and can beretrieved using get_led_device_info.sh script from tools/leds; generallythis section is expected mostly for LEDs that are somehow associated withother devices.

  • color:

    one of LED_COLOR_ID_* definitions from the headerinclude/dt-bindings/leds/common.h.

  • function:

    one of LED_FUNCTION_* definitions from the headerinclude/dt-bindings/leds/common.h.

If required color or function is missing, please submit a patchtolinux-leds@vger.kernel.org.

It is possible that more than one LED with the same color and function willbe required for given platform, differing only with an ordinal number.In this case it is preferable to just concatenate the predefined LED_FUNCTION_*name with required “-N” suffix in the driver. fwnode based drivers can usefunction-enumerator property for that and then the concatenation will be handledautomatically by the LED core upon LED class device registration.

LED subsystem has also a protection against name clash, that may occurwhen LED class device is created by a driver of hot-pluggable device andit doesn’t provide unique devicename section. In this case numericalsuffix (e.g. “_1”, “_2”, “_3” etc.) is added to the requested LED classdevice name.

There might be still LED class drivers around using vendor or product namefor devicename, but this approach is now deprecated as it doesn’t conveyany added value. Product information can be found in other places in sysfs(see tools/leds/get_led_device_info.sh).

Examples of proper LED names:

  • “red:disk”

  • “white:flash”

  • “red:indicator”

  • “phy1:green:wlan”

  • “phy3::wlan”

  • “:kbd_backlight”

  • “input5::kbd_backlight”

  • “input3::numlock”

  • “input3::scrolllock”

  • “input3::capslock”

  • “mmc1::status”

  • “white:status”

get_led_device_info.sh script can be used for verifying if the LED namemeets the requirements pointed out here. It performs validation of the LED classdevicename sections and gives hints on expected value for a section in casethe validation fails for it. So far the script supports validationof associations between LEDs and following types of devices:

  • input devices

  • ieee80211 compliant USB devices

The script is open to extensions.

There have been calls for LED properties such as color to be exported asindividual led class attributes. As a solution which doesn’t incur as muchoverhead, I suggest these become part of the device name. The naming schemeabove leaves scope for further attributes should they be needed. If sectionsof the name don’t apply, just leave that section blank.

Brightness setting API

LED subsystem core exposes following API for setting brightness:

  • led_set_brightness:

    it is guaranteed not to sleep, passing LED_OFF stopsblinking,

  • led_set_brightness_sync:

    for use cases when immediate effect is desired -it can block the caller for the time required for accessingdevice registers and can sleep, passing LED_OFF stops hardwareblinking, returns -EBUSY if software blink fallback is enabled.

LED registration API

A driver wanting to register a LED classdev for use by other drivers /userspace needs to allocate and fill a led_classdevstructand then call[devm_]led_classdev_register. If the non devm version is used the drivermust call led_classdev_unregister from its remove function beforefree-ing the led_classdev struct.

If the driver can detect hardware initiated brightness changes and thuswants to have a brightness_hw_changed attribute then the LED_BRIGHT_HW_CHANGEDflag must be set in flags before registering. Callingled_classdev_notify_brightness_hw_changed on a classdev not registered withthe LED_BRIGHT_HW_CHANGED flag is a bug and will trigger a WARN_ON.

Hardware accelerated blink of LEDs

Some LEDs can be programmed to blink without any CPU interaction. Tosupport this feature, a LED driver can optionally implement theblink_set() function (see <linux/leds.h>). To set an LED to blinking,however, it is better to use the API functionled_blink_set(), as itwill check and implement software fallback if necessary.

To turn off blinking, use the API functionled_brightness_set()with brightness value LED_OFF, which should stop any softwaretimers that may have been required for blinking.

Theblink_set() function should choose a user friendly blinking valueif it is called with*delay_on==0 &&*delay_off==0 parameters. In thiscase the driver should give back the chosen value through delay_on anddelay_off parameters to the leds subsystem.

Setting the brightness to zero withbrightness_set() callback functionshould completely turn off the LED and cancel the previously programmedhardware blinking function, if any.

Hardware driven LEDs

Some LEDs can be programmed to be driven by hardware. This is notlimited to blink but also to turn off or on autonomously.To support this feature, a LED needs to implement various additionalops and needs to declare specific support for the supported triggers.

With hw control we refer to the LED driven by hardware.

LED driver must define the following value to support hw control:

  • hw_control_trigger:

    unique trigger name supported by the LED in hw controlmode.

LED driver must implement the following API to support hw control:
  • hw_control_is_supported:

    check if the flags passed by the supported trigger canbe parsed and activate hw control on the LED.

    Return 0 if the passed flags mask is supported andcan be set withhw_control_set().

    If the passed flags mask is not supported -EOPNOTSUPPmust be returned, the LED trigger will use softwarefallback in this case.

    Return a negative error in case of any other error likedevice not ready or timeouts.

  • hw_control_set:

    activate hw control. LED driver will use the providedflags passed from the supported trigger, parse them toa set of mode and setup the LED to be driven by hardwarefollowing the requested modes.

    Set LED_OFF via the brightness_set to deactivate hw control.

    Return 0 on success, a negative error number on failing toapply flags.

  • hw_control_get:

    get active modes from a LED already in hw control, parsethem and set in flags the current active flags for thesupported trigger.

    Return 0 on success, a negative error number on failingparsing the initial mode.Error from this function is NOT FATAL as the device maybe in a not supported initial state by the attached LEDtrigger.

  • hw_control_get_device:

    return the device associated with the LED driver inhw control. A trigger might use this to match thereturned device from this function with a configureddevice for the trigger as the source for blinkingevents and correctly enable hw control.(example a netdev trigger configured to blink for aparticular dev match the returned dev from get_deviceto set hw control)

    Returns a pointer to astructdevice or NULL if nothingis currently attached.

LED driver can activate additional modes by default to workaround theimpossibility of supporting each different mode on the supported trigger.Examples are hardcoding the blink speed to a set interval, enable specialfeature like bypassing blink if some requirements are not met.

A trigger should first check if the hw control API are supported by the LEDdriver and check if the trigger is supported to verify if hw control is possible,use hw_control_is_supported to check if the flags are supported and only atthe end use hw_control_set to activate hw control.

A trigger can use hw_control_get to check if a LED is already in hw controland init their flags.

When the LED is in hw control, no software blink is possible and doing sowill effectively disable hw control.

Known Issues

The LED Trigger core cannot be a module as the simple trigger functionswould cause nightmare dependency issues. I see this as a minor issuecompared to the benefits the simple trigger functionality brings. Therest of the LED subsystem can be modular.