code:
.. _kernel_hacking_hack:

============================================
Unreliable Guide To Hacking The Linux Kernel
============================================

:Author: Rusty Russell

Introduction
============

Welcome, gentle reader, to Rusty's Remarkably Unreliable Guide to Linux
Kernel Hacking. This document describes the common routines and general
requirements for kernel code: its goal is to serve as a primer for Linux
kernel development for experienced C programmers. I avoid implementation
details: that's what the code is for, and I ignore whole tracts of
useful routines.

Before you read this, please understand that I never wanted to write
this document, being grossly under-qualified, but I always wanted to
read it, and this was the only way. I hope it will grow into a
compendium of best practice, common starting points and random
information.

The Players
===========

At any time each of the CPUs in a system can be:

-  not associated with any process, serving a hardware interrupt;

-  not associated with any process, serving a softirq or tasklet;

-  running in kernel space, associated with a process (user context);

-  running a process in user space.

There is an ordering between these. The bottom two can preempt each
other, but above that is a strict hierarchy: each can only be preempted
by the ones above it. For example, while a softirq is running on a CPU,
no other softirq will preempt it, but a hardware interrupt can. However,
any other CPUs in the system execute independently.

We'll see a number of ways that the user context can block interrupts,
to become truly non-preemptable.

User Context
------------

User context is when you are coming in from a system call or other trap:
like userspace, you can be preempted by more important tasks and by
interrupts. You can sleep, by calling :c:func:`schedule()`.

.. note::

    You are always in user context on module load and unload, and on
    operations on the block device layer.

In user context, the ``current`` pointer (indicating the task we are
currently executing) is valid, and :c:func:`in_interrupt()`
(``include/linux/preempt.h``) is false.

.. warning::

    Beware that if you have preemption or softirqs disabled (see below),
    :c:func:`in_interrupt()` will return a false positive.

Hardware Interrupts (Hard IRQs)
-------------------------------

Timer ticks, network cards and keyboard are examples of real hardware
which produce interrupts at any time. The kernel runs interrupt
handlers, which services the hardware. The kernel guarantees that this
handler is never re-entered: if the same interrupt arrives, it is queued
(or dropped). Because it disables interrupts, this handler has to be
fast: frequently it simply acknowledges the interrupt, marks a 'software
interrupt' for execution and exits.

You can tell you are in a hardware interrupt, because in_hardirq() returns
true.

.. warning::

    Beware that this will return a false positive if interrupts are
    disabled (see below).

Software Interrupt Context: Softirqs and Tasklets
-------------------------------------------------

Whenever a system call is about to return to userspace, or a hardware
interrupt handler exits, any 'software interrupts' which are marked
pending (usually by hardware interrupts) are run (``kernel/softirq.c``).

Much of the real interrupt handling work is done here. Early in the
transition to SMP, there were only 'bottom halves' (BHs), which didn't
take advantage of multiple CPUs. Shortly after we switched from wind-up
computers made of match-sticks and snot, we abandoned this limitation
and switched to 'softirqs'.

``include/linux/interrupt.h`` lists the different softirqs. A very
important softirq is the timer softirq (``include/linux/timer.h``): you
can register to have it call functions for you in a given length of
time.

Softirqs are often a pain to deal with, since the same softirq will run
simultaneously on more than one CPU. For this reason, tasklets
(``include/linux/interrupt.h``) are more often used: they are
dynamically-registrable (meaning you can have as many as you want), and
they also guarantee that any tasklet will only run on one CPU at any
time, although different tasklets can run simultaneously.

.. warning::

    The name 'tasklet' is misleading: they have nothing to do with
    'tasks'.

You can tell you are in a softirq (or tasklet) using the
:c:func:`in_softirq()` macro (``include/linux/preempt.h``).

.. warning::

    Beware that this will return a false positive if a
    :ref:`bottom half lock <local_bh_disable>` is held.

Some Basic Rules
================

No memory protection
    If you corrupt memory, whether in user context or interrupt context,
    the whole machine will crash. Are you sure you can't do what you
    want in userspace?

No floating point or MMX
    The FPU context is not saved; even in user context the FPU state
    probably won't correspond with the current process: you would mess
    with some user process' FPU state. If you really want to do this,
    you would have to explicitly save/restore the full FPU state (and
    avoid context switches). It is generally a bad idea; use fixed point
    arithmetic first.

A rigid stack limit
    Depending on configuration options the kernel stack is about 3K to
    6K for most 32-bit architectures: it's about 14K on most 64-bit
    archs, and often shared with interrupts so you can't use it all.
    Avoid deep recursion and huge local arrays on the stack (allocate
    them dynamically instead).

The Linux kernel is portable
    Let's keep it that way. Your code should be 64-bit clean, and
    endian-independent. You should also minimize CPU specific stuff,
    e.g. inline assembly should be cleanly encapsulated and minimized to
    ease porting. Generally it should be restricted to the
    architecture-dependent part of the kernel tree.

ioctls: Not writing a new system call
=====================================

A system call generally looks like this::

    asmlinkage long sys_mycall(int arg)
    {
            return 0;
    }

First, in most cases you don't want to create a new system call. You
create a character device and implement an appropriate ioctl for it.
This is much more flexible than system calls, doesn't have to be entered
in every architecture's ``include/asm/unistd.h`` and
``arch/kernel/entry.S`` file, and is much more likely to be accepted by
Linus.

If all your routine does is read or write some parameter, consider
implementing a :c:func:`sysfs()` interface instead.

Inside the ioctl you're in user context to a process. When a error
occurs you return a negated errno (see
``include/uapi/asm-generic/errno-base.h``,
``include/uapi/asm-generic/errno.h`` and ``include/linux/errno.h``),
otherwise you return 0.

After you slept you should check if a signal occurred: the Unix/Linux
way of handling signals is to temporarily exit the system call with the
``-ERESTARTSYS`` error. The system call entry code will switch back to
user context, process the signal handler and then your system call will
be restarted (unless the user disabled that). So you should be prepared
to process the restart, e.g. if you're in the middle of manipulating
some data structure.

::

    if (signal_pending(current))
            return -ERESTARTSYS;

If you're doing longer computations: first think userspace. If you
**really** want to do it in kernel you should regularly check if you need
to give up the CPU (remember there is cooperative multitasking per CPU).
Idiom::

    cond_resched(); /* Will sleep */

A short note on interface design: the UNIX system call motto is "Provide
mechanism not policy".

Recipes for Deadlock
====================

You cannot call any routines which may sleep, unless:

-  You are in user context.

-  You do not own any spinlocks.

-  You have interrupts enabled (actually, Andi Kleen says that the
   scheduling code will enable them for you, but that's probably not
   what you wanted).

Note that some functions may sleep implicitly: common ones are the user
space access functions (\*_user) and memory allocation functions
without ``GFP_ATOMIC``.

You should always compile your kernel ``CONFIG_DEBUG_ATOMIC_SLEEP`` on,
and it will warn you if you break these rules. If you **do** break the
rules, you will eventually lock up your box.

Really.

Common Routines
===============

:c:func:`printk()`
------------------

Defined in ``include/linux/printk.h``

:c:func:`printk()` feeds kernel messages to the console, dmesg, and
the syslog daemon. It is useful for debugging and reporting errors, and
can be used inside interrupt context, but use with caution: a machine
which has its console flooded with printk messages is unusable. It uses
a format string mostly compatible with ANSI C printf, and C string
concatenation to give it a first "priority" argument::

    printk(KERN_INFO "i = %u\n", i);

See ``include/linux/kern_levels.h``; for other ``KERN_`` values; these are
interpreted by syslog as the level. Special case: for printing an IP
address use::

    __be32 ipaddress;
    printk(KERN_INFO "my ip: %pI4\n", &ipaddress);

:c:func:`printk()` internally uses a 1K buffer and does not catch
overruns. Make sure that will be enough.

.. note::

    You will know when you are a real kernel hacker when you start
    typoing printf as printk in your user programs :)

.. note::

    Another sidenote: the original Unix Version 6 sources had a comment
    on top of its printf function: "Printf should not be used for
    chit-chat". You should follow that advice.

:c:func:`copy_to_user()` / :c:func:`copy_from_user()` / :c:func:`get_user()` / :c:func:`put_user()`
---------------------------------------------------------------------------------------------------

Defined in ``include/linux/uaccess.h`` / ``asm/uaccess.h``

**[SLEEPS]**

:c:func:`put_user()` and :c:func:`get_user()` are used to get
and put single values (such as an int, char, or long) from and to
userspace. A pointer into userspace should never be simply dereferenced:
data should be copied using these routines. Both return ``-EFAULT`` or
0.

:c:func:`copy_to_user()` and :c:func:`copy_from_user()` are
more general: they copy an arbitrary amount of data to and from
userspace.

.. warning::

    Unlike :c:func:`put_user()` and :c:func:`get_user()`, they
    return the amount of uncopied data (ie. 0 still means success).

[Yes, this objectionable interface makes me cringe. The flamewar comes
up every year or so. --RR.]

The functions may sleep implicitly. This should never be called outside
user context (it makes no sense), with interrupts disabled, or a
spinlock held.

:c:func:`kmalloc()`/:c:func:`kfree()`
-------------------------------------

Defined in ``include/linux/slab.h``

**[MAY SLEEP: SEE BELOW]**

These routines are used to dynamically request pointer-aligned chunks of
memory, like malloc and free do in userspace, but
:c:func:`kmalloc()` takes an extra flag word. Important values:

``GFP_KERNEL``
    May sleep and swap to free memory. Only allowed in user context, but
    is the most reliable way to allocate memory.

``GFP_ATOMIC``
    Don't sleep. Less reliable than ``GFP_KERNEL``, but may be called
    from interrupt context. You should **really** have a good
    out-of-memory error-handling strategy.

``GFP_DMA``
    Allocate ISA DMA lower than 16MB. If you don't know what that is you
    don't need it. Very unreliable.

If you see a sleeping function called from invalid context warning
message, then maybe you called a sleeping allocation function from
interrupt context without ``GFP_ATOMIC``. You should really fix that.
Run, don't walk.

If you are allocating at least ``PAGE_SIZE`` (``asm/page.h`` or
``asm/page_types.h``) bytes, consider using :c:func:`__get_free_pages()`
(``include/linux/gfp.h``). It takes an order argument (0 for page sized,
1 for double page, 2 for four pages etc.) and the same memory priority
flag word as above.

If you are allocating more than a page worth of bytes you can use
:c:func:`vmalloc()`. It'll allocate virtual memory in the kernel
map. This block is not contiguous in physical memory, but the MMU makes
it look like it is for you (so it'll only look contiguous to the CPUs,
not to external device drivers). If you really need large physically
contiguous memory for some weird device, you have a problem: it is
poorly supported in Linux because after some time memory fragmentation
in a running kernel makes it hard. The best way is to allocate the block
early in the boot process via the :c:func:`alloc_bootmem()`
routine.

Before inventing your own cache of often-used objects consider using a
slab cache in ``include/linux/slab.h``

:c:macro:`current`
------------------

Defined in ``include/asm/current.h``

This global variable (really a macro) contains a pointer to the current
task structure, so is only valid in user context. For example, when a
process makes a system call, this will point to the task structure of
the calling process. It is **not NULL** in interrupt context.

:c:func:`mdelay()`/:c:func:`udelay()`
-------------------------------------

Defined in ``include/asm/delay.h`` / ``include/linux/delay.h``

The :c:func:`udelay()` and :c:func:`ndelay()` functions can be
used for small pauses. Do not use large values with them as you risk
overflow - the helper function :c:func:`mdelay()` is useful here, or
consider :c:func:`msleep()`.

:c:func:`cpu_to_be32()`/:c:func:`be32_to_cpu()`/:c:func:`cpu_to_le32()`/:c:func:`le32_to_cpu()`
-----------------------------------------------------------------------------------------------

Defined in ``include/asm/byteorder.h``

The :c:func:`cpu_to_be32()` family (where the "32" can be replaced
by 64 or 16, and the "be" can be replaced by "le") are the general way
to do endian conversions in the kernel: they return the converted value.
All variations supply the reverse as well:
:c:func:`be32_to_cpu()`, etc.

There are two major variations of these functions: the pointer
variation, such as :c:func:`cpu_to_be32p()`, which take a pointer
to the given type, and return the converted value. The other variation
is the "in-situ" family, such as :c:func:`cpu_to_be32s()`, which
convert value referred to by the pointer, and return void.

:c:func:`local_irq_save()`/:c:func:`local_irq_restore()`
--------------------------------------------------------

Defined in ``include/linux/irqflags.h``

These routines disable hard interrupts on the local CPU, and restore
them. They are reentrant; saving the previous state in their one
``unsigned long flags`` argument. If you know that interrupts are
enabled, you can simply use :c:func:`local_irq_disable()` and
:c:func:`local_irq_enable()`.

.. _local_bh_disable:

:c:func:`local_bh_disable()`/:c:func:`local_bh_enable()`
--------------------------------------------------------

Defined in ``include/linux/bottom_half.h``

These routines disable soft interrupts on the local CPU, and restore
them. They are reentrant; if soft interrupts were disabled before, they
will still be disabled after this pair of functions has been called.
They prevent softirqs and tasklets from running on the current CPU.

:c:func:`smp_processor_id()`
----------------------------

Defined in ``include/linux/smp.h``

:c:func:`get_cpu()` disables preemption (so you won't suddenly get
moved to another CPU) and returns the current processor number, between
0 and ``NR_CPUS``. Note that the CPU numbers are not necessarily
continuous. You return it again with :c:func:`put_cpu()` when you
are done.

If you know you cannot be preempted by another task (ie. you are in
interrupt context, or have preemption disabled) you can use
smp_processor_id().

``__init``/``__exit``/``__initdata``
------------------------------------

Defined in  ``include/linux/init.h``

After boot, the kernel frees up a special section; functions marked with
``__init`` and data structures marked with ``__initdata`` are dropped
after boot is complete: similarly modules discard this memory after
initialization. ``__exit`` is used to declare a function which is only
required on exit: the function will be dropped if this file is not
compiled as a module. See the header file for use. Note that it makes no
sense for a function marked with ``__init`` to be exported to modules
with :c:func:`EXPORT_SYMBOL()` or :c:func:`EXPORT_SYMBOL_GPL()`- this
will break.

:c:func:`__initcall()`/:c:func:`module_init()`
----------------------------------------------

Defined in  ``include/linux/init.h`` / ``include/linux/module.h``

Many parts of the kernel are well served as a module
(dynamically-loadable parts of the kernel). Using the
:c:func:`module_init()` and :c:func:`module_exit()` macros it
is easy to write code without #ifdefs which can operate both as a module
or built into the kernel.

The :c:func:`module_init()` macro defines which function is to be
called at module insertion time (if the file is compiled as a module),
or at boot time: if the file is not compiled as a module the
:c:func:`module_init()` macro becomes equivalent to
:c:func:`__initcall()`, which through linker magic ensures that
the function is called on boot.

The function can return a negative error number to cause module loading
to fail (unfortunately, this has no effect if the module is compiled
into the kernel). This function is called in user context with
interrupts enabled, so it can sleep.

:c:func:`module_exit()`
-----------------------

Defined in  ``include/linux/module.h``

This macro defines the function to be called at module removal time (or
never, in the case of the file compiled into the kernel). It will only
be called if the module usage count has reached zero. This function can
also sleep, but cannot fail: everything must be cleaned up by the time
it returns.

Note that this macro is optional: if it is not present, your module will
not be removable (except for 'rmmod -f').

:c:func:`try_module_get()`/:c:func:`module_put()`
-------------------------------------------------

Defined in ``include/linux/module.h``

These manipulate the module usage count, to protect against removal (a
module also can't be removed if another module uses one of its exported
symbols: see below). Before calling into module code, you should call
:c:func:`try_module_get()` on that module: if it fails, then the
module is being removed and you should act as if it wasn't there.
Otherwise, you can safely enter the module, and call
:c:func:`module_put()` when you're finished.

Most registerable structures have an owner field, such as in the
:c:type:`struct file_operations <file_operations>` structure.
Set this field to the macro ``THIS_MODULE``.

Wait Queues ``include/linux/wait.h``
====================================

**[SLEEPS]**

A wait queue is used to wait for someone to wake you up when a certain
condition is true. They must be used carefully to ensure there is no
race condition. You declare a :c:type:`wait_queue_head_t`, and then processes
which want to wait for that condition declare a :c:type:`wait_queue_entry_t`
referring to themselves, and place that in the queue.

Declaring
---------

You declare a ``wait_queue_head_t`` using the
:c:func:`DECLARE_WAIT_QUEUE_HEAD()` macro, or using the
:c:func:`init_waitqueue_head()` routine in your initialization
code.

Queuing
-------

Placing yourself in the waitqueue is fairly complex, because you must
put yourself in the queue before checking the condition. There is a
macro to do this: :c:func:`wait_event_interruptible()`
(``include/linux/wait.h``) The first argument is the wait queue head, and
the second is an expression which is evaluated; the macro returns 0 when
this expression is true, or ``-ERESTARTSYS`` if a signal is received. The
:c:func:`wait_event()` version ignores signals.

Waking Up Queued Tasks
----------------------

Call :c:func:`wake_up()` (``include/linux/wait.h``), which will wake
up every process in the queue. The exception is if one has
``TASK_EXCLUSIVE`` set, in which case the remainder of the queue will
not be woken. There are other variants of this basic function available
in the same header.

Atomic Operations
=================

Certain operations are guaranteed atomic on all platforms. The first
class of operations work on :c:type:`atomic_t` (``include/asm/atomic.h``);
this contains a signed integer (at least 32 bits long), and you must use
these functions to manipulate or read :c:type:`atomic_t` variables.
:c:func:`atomic_read()` and :c:func:`atomic_set()` get and set
the counter, :c:func:`atomic_add()`, :c:func:`atomic_sub()`,
:c:func:`atomic_inc()`, :c:func:`atomic_dec()`, and
:c:func:`atomic_dec_and_test()` (returns true if it was
decremented to zero).

Yes. It returns true (i.e. != 0) if the atomic variable is zero.

Note that these functions are slower than normal arithmetic, and so
should not be used unnecessarily.

The second class of atomic operations is atomic bit operations on an
``unsigned long``, defined in ``include/linux/bitops.h``. These
operations generally take a pointer to the bit pattern, and a bit
number: 0 is the least significant bit. :c:func:`set_bit()`,
:c:func:`clear_bit()` and :c:func:`change_bit()` set, clear,
and flip the given bit. :c:func:`test_and_set_bit()`,
:c:func:`test_and_clear_bit()` and
:c:func:`test_and_change_bit()` do the same thing, except return
true if the bit was previously set; these are particularly useful for
atomically setting flags.

It is possible to call these operations with bit indices greater than
``BITS_PER_LONG``. The resulting behavior is strange on big-endian
platforms though so it is a good idea not to do this.

Symbols
=======

Within the kernel proper, the normal linking rules apply (ie. unless a
symbol is declared to be file scope with the ``static`` keyword, it can
be used anywhere in the kernel). However, for modules, a special
exported symbol table is kept which limits the entry points to the
kernel proper. Modules can also export symbols.

:c:func:`EXPORT_SYMBOL()`
-------------------------

Defined in ``include/linux/export.h``

This is the classic method of exporting a symbol: dynamically loaded
modules will be able to use the symbol as normal.

:c:func:`EXPORT_SYMBOL_GPL()`
-----------------------------

Defined in ``include/linux/export.h``

Similar to :c:func:`EXPORT_SYMBOL()` except that the symbols
exported by :c:func:`EXPORT_SYMBOL_GPL()` can only be seen by
modules with a :c:func:`MODULE_LICENSE()` that specifies a GPL
compatible license. It implies that the function is considered an
internal implementation issue, and not really an interface. Some
maintainers and developers may however require EXPORT_SYMBOL_GPL()
when adding any new APIs or functionality.

:c:func:`EXPORT_SYMBOL_NS()`
----------------------------

Defined in ``include/linux/export.h``

This is the variant of `EXPORT_SYMBOL()` that allows specifying a symbol
namespace. Symbol Namespaces are documented in
Documentation/core-api/symbol-namespaces.rst

:c:func:`EXPORT_SYMBOL_NS_GPL()`
--------------------------------

Defined in ``include/linux/export.h``

This is the variant of `EXPORT_SYMBOL_GPL()` that allows specifying a symbol
namespace. Symbol Namespaces are documented in
Documentation/core-api/symbol-namespaces.rst

Routines and Conventions
========================

Double-linked lists ``include/linux/list.h``
--------------------------------------------

There used to be three sets of linked-list routines in the kernel
headers, but this one is the winner. If you don't have some particular
pressing need for a single list, it's a good choice.

In particular, :c:func:`list_for_each_entry()` is useful.

Return Conventions
------------------

For code called in user context, it's very common to defy C convention,
and return 0 for success, and a negative error number (eg. ``-EFAULT``) for
failure. This can be unintuitive at first, but it's fairly widespread in
the kernel.

Using :c:func:`ERR_PTR()` (``include/linux/err.h``) to encode a
negative error number into a pointer, and :c:func:`IS_ERR()` and
:c:func:`PTR_ERR()` to get it back out again: avoids a separate
pointer parameter for the error number. Icky, but in a good way.

Breaking Compilation
--------------------

Linus and the other developers sometimes change function or structure
names in development kernels; this is not done just to keep everyone on
their toes: it reflects a fundamental change (eg. can no longer be
called with interrupts on, or does extra checks, or doesn't do checks
which were caught before). Usually this is accompanied by a fairly
complete note to the appropriate kernel development mailing list; search
the archives. Simply doing a global replace on the file usually makes
things **worse**.

Initializing structure members
------------------------------

The preferred method of initializing structures is to use designated
initialisers, as defined by ISO C99, eg::

    static struct block_device_operations opt_fops = {
            .open               = opt_open,
            .release            = opt_release,
            .ioctl              = opt_ioctl,
            .check_media_change = opt_media_change,
    };

This makes it easy to grep for, and makes it clear which structure
fields are set. You should do this because it looks cool.

GNU Extensions
--------------

GNU Extensions are explicitly allowed in the Linux kernel. Note that
some of the more complex ones are not very well supported, due to lack
of general use, but the following are considered standard (see the GCC
info page section "C Extensions" for more details - Yes, really the info
page, the man page is only a short summary of the stuff in info).

-  Inline functions

-  Statement expressions (ie. the ({ and }) constructs).

-  Declaring attributes of a function / variable / type
   (__attribute__)

-  typeof

-  Zero length arrays

-  Macro varargs

-  Arithmetic on void pointers

-  Non-Constant initializers

-  Assembler Instructions (not outside arch/ and include/asm/)

-  Function names as strings (__func__).

-  __builtin_constant_p()

Be wary when using long long in the kernel, the code gcc generates for
it is horrible and worse: division and multiplication does not work on
i386 because the GCC runtime functions for it are missing from the
kernel environment.

C++
---

Using C++ in the kernel is usually a bad idea, because the kernel does
not provide the necessary runtime environment and the include files are
not tested for it. It is still possible, but not recommended. If you
really want to do this, forget about exceptions at least.

#if
---

It is generally considered cleaner to use macros in header files (or at
the top of .c files) to abstract away functions rather than using \`#if'
pre-processor statements throughout the source code.

Putting Your Stuff in the Kernel
================================

In order to get your stuff into shape for official inclusion, or even to
make a neat patch, there's administrative work to be done:

-  Figure out who are the owners of the code you've been modifying. Look
   at the top of the source files, inside the ``MAINTAINERS`` file, and
   last of all in the ``CREDITS`` file. You should coordinate with these
   people to make sure you're not duplicating effort, or trying something
   that's already been rejected.

   Make sure you put your name and email address at the top of any files
   you create or modify significantly. This is the first place people
   will look when they find a bug, or when **they** want to make a change.

-  Usually you want a configuration option for your kernel hack. Edit
   ``Kconfig`` in the appropriate directory. The Config language is
   simple to use by cut and paste, and there's complete documentation in
   ``Documentation/kbuild/kconfig-language.rst``.

   In your description of the option, make sure you address both the
   expert user and the user who knows nothing about your feature.
   Mention incompatibilities and issues here. **Definitely** end your
   description with “if in doubt, say N” (or, occasionally, \`Y'); this
   is for people who have no idea what you are talking about.

-  Edit the ``Makefile``: the CONFIG variables are exported here so you
   can usually just add a "obj-$(CONFIG_xxx) += xxx.o" line. The syntax
   is documented in ``Documentation/kbuild/makefiles.rst``.

-  Put yourself in ``CREDITS`` if you consider what you've done
   noteworthy, usually beyond a single file (your name should be at the
   top of the source files anyway). ``MAINTAINERS`` means you want to be
   consulted when changes are made to a subsystem, and hear about bugs;
   it implies a more-than-passing commitment to some part of the code.

-  Finally, don't forget to read
   ``Documentation/process/submitting-patches.rst``

Kernel Cantrips
===============

Some favorites from browsing the source. Feel free to add to this list.

``arch/x86/include/asm/delay.h``::

    #define ndelay(n) (__builtin_constant_p(n) ? \
            ((n) > 20000 ? __bad_ndelay() : __const_udelay((n) * 5ul)) : \
            __ndelay(n))

``include/linux/fs.h``::

    /*
     * Kernel pointers have redundant information, so we can use a
     * scheme where we can return either an error code or a dentry
     * pointer with the same return value.
     *
     * This should be a per-architecture thing, to allow different
     * error and pointer decisions.
     */
     #define ERR_PTR(err)    ((void *)((long)(err)))
     #define PTR_ERR(ptr)    ((long)(ptr))
     #define IS_ERR(ptr)     ((unsigned long)(ptr) > (unsigned long)(-1000))

``arch/x86/include/asm/uaccess_32.h:``::

    #define copy_to_user(to,from,n)                         \
            (__builtin_constant_p(n) ?                      \
             __constant_copy_to_user((to),(from),(n)) :     \
             __generic_copy_to_user((to),(from),(n)))

``arch/sparc/kernel/head.S:``::

    /*
     * Sun people can't spell worth damn. "compatability" indeed.
     * At least we *know* we can't spell, and use a spell-checker.
     */

    /* Uh, actually Linus it is I who cannot spell. Too much murky
     * Sparc assembly will do this to ya.
     */
    C_LABEL(cputypvar):
            .asciz "compatibility"

    /* Tested on SS-5, SS-10. Probably someone at Sun applied a spell-checker. */
            .align 4
    C_LABEL(cputypvar_sun4m):
            .asciz "compatible"

``arch/sparc/lib/checksum.S:``::

            /* Sun, you just can't beat me, you just can't.  Stop trying,
             * give up.  I'm serious, I am going to kick the living shit
             * out of you, game over, lights out.
             */

Thanks
======

Thanks to Andi Kleen for the idea, answering my questions, fixing my
mistakes, filling content, etc. Philipp Rumpf for more spelling and
clarity fixes, and some excellent non-obvious points. Werner Almesberger
for giving me a great summary of :c:func:`disable_irq()`, and Jes
Sorensen and Andrea Arcangeli added caveats. Michael Elizabeth Chastain
for checking and adding to the Configure section. Telsa Gwynne for
teaching me DocBook.


code:
.. _kernel_hacking:

=====================
Kernel Hacking Guides
=====================

.. toctree::
   :maxdepth: 2

   hacking
   locking

repo_name: angery/linux


code:
.. SPDX-License-Identifier: GPL-2.0

====
LEDs
====

.. toctree::
   :maxdepth: 1

   leds-class
   leds-class-flash
   leds-class-multicolor
   ledtrig-oneshot
   ledtrig-transient
   ledtrig-usbport

   uleds

   leds-blinkm
   leds-el15203000
   leds-lm3556
   leds-lp3944
   leds-lp5521
   leds-lp5523
   leds-lp5562
   leds-lp55xx
   leds-mlxcpld
   leds-sc27xx


code:
==================
Leds BlinkM driver
==================

The leds-blinkm driver supports the devices of the BlinkM family.

They are RGB-LED modules driven by a (AT)tiny microcontroller and
communicate through I2C. The default address of these modules is
0x09 but this can be changed through a command. By this you could
dasy-chain up to 127 BlinkMs on an I2C bus.

The device accepts RGB and HSB color values through separate commands.
Also you can store blinking sequences as "scripts" in
the controller and run them. Also fading is an option.

The interface this driver provides is 2-fold:

a) LED class interface for use with triggers
############################################

The registration follows the scheme::

  blinkm-<i2c-bus-nr>-<i2c-device-nr>-<color>

  $ ls -h /sys/class/leds/blinkm-6-*
  /sys/class/leds/blinkm-6-9-blue:
  brightness  device  max_brightness  power  subsystem  trigger  uevent

  /sys/class/leds/blinkm-6-9-green:
  brightness  device  max_brightness  power  subsystem  trigger  uevent

  /sys/class/leds/blinkm-6-9-red:
  brightness  device  max_brightness  power  subsystem  trigger  uevent

(same is /sys/bus/i2c/devices/6-0009/leds)

We can control the colors separated into red, green and blue and
assign triggers on each color.

E.g.::

  $ cat blinkm-6-9-blue/brightness
  05

  $ echo 200 > blinkm-6-9-blue/brightness
  $

  $ modprobe ledtrig-heartbeat
  $ echo heartbeat > blinkm-6-9-green/trigger
  $

b) Sysfs group to control rgb, fade, hsb, scripts ...
#####################################################

This extended interface is available as folder blinkm
in the sysfs folder of the I2C device.
E.g. below /sys/bus/i2c/devices/6-0009/blinkm

  $ ls -h /sys/bus/i2c/devices/6-0009/blinkm/
  blue  green  red  test

Currently supported is just setting red, green, blue
and a test sequence.

E.g.::

  $ cat *
  00
  00
  00
  #Write into test to start test sequence!#

  $ echo 1 > test
  $

  $ echo 255 > red
  $

as of 6/2012

dl9pf <at> gmx <dot> de


code:
==============================
Flash LED handling under Linux
==============================

Some LED devices provide two modes - torch and flash. In the LED subsystem
those modes are supported by LED class (see Documentation/leds/leds-class.rst)
and LED Flash class respectively. The torch mode related features are enabled
by default and the flash ones only if a driver declares it by setting
LED_DEV_CAP_FLASH flag.

In order to enable the support for flash LEDs CONFIG_LEDS_CLASS_FLASH symbol
must be defined in the kernel config. A LED Flash class driver must be
registered in the LED subsystem with led_classdev_flash_register function.

Following sysfs attributes are exposed for controlling flash LED devices:
(see Documentation/ABI/testing/sysfs-class-led-flash)

	- flash_brightness
	- max_flash_brightness
	- flash_timeout
	- max_flash_timeout
	- flash_strobe
	- flash_fault

V4L2 flash wrapper for flash LEDs
=================================

A LED subsystem driver can be controlled also from the level of VideoForLinux2
subsystem. In order to enable this CONFIG_V4L2_FLASH_LED_CLASS symbol has to
be defined in the kernel config.

The driver must call the v4l2_flash_init function to get registered in the
V4L2 subsystem. The function takes six arguments:

- dev:
	flash device, e.g. an I2C device
- of_node:
	of_node of the LED, may be NULL if the same as device's
- fled_cdev:
	LED flash class device to wrap
- iled_cdev:
	LED flash class device representing indicator LED associated with
	fled_cdev, may be NULL
- ops:
	V4L2 specific ops

	* external_strobe_set
		defines the source of the flash LED strobe -
		V4L2_CID_FLASH_STROBE control or external source, typically
		a sensor, which makes it possible to synchronise the flash
		strobe start with exposure start,
	* intensity_to_led_brightness and led_brightness_to_intensity
		perform
		enum led_brightness <-> V4L2 intensity conversion in a device
		specific manner - they can be used for devices with non-linear
		LED current scale.
- config:
	configuration for V4L2 Flash sub-device

	* dev_name
		the name of the media entity, unique in the system,
	* flash_faults
		bitmask of flash faults that the LED flash class
		device can report; corresponding LED_FAULT* bit definitions are
		available in <linux/led-class-flash.h>,
	* torch_intensity
		constraints for the LED in TORCH mode
		in microamperes,
	* indicator_intensity
		constraints for the indicator LED
		in microamperes,
	* has_external_strobe
		determines whether the flash strobe source
		can be switched to external,

On remove the v4l2_flash_release function has to be called, which takes one
argument - struct v4l2_flash pointer returned previously by v4l2_flash_init.
This function can be safely called with NULL or error pointer argument.

Please refer to drivers/leds/leds-max77693.c for an exemplary usage of the
v4l2 flash wrapper.

Once the V4L2 sub-device is registered by the driver which created the Media
controller device, the sub-device node acts just as a node of a native V4L2
flash API device would. The calls are simply routed to the LED flash API.

Opening the V4L2 flash sub-device makes the LED subsystem sysfs interface
unavailable. The interface is re-enabled after the V4L2 flash sub-device
is closed.


code:
.. SPDX-License-Identifier: GPL-2.0

====================================
Multicolor LED handling under Linux
====================================

Description
===========
The multicolor class groups monochrome LEDs and allows controlling two
aspects of the final combined color: hue and lightness. The former is
controlled via the multi_intensity array file and the latter is controlled
via brightness file.

Multicolor Class Control
========================
The multicolor class presents files that groups the colors as indexes in an
array.  These files are children under the LED parent node created by the
led_class framework.  The led_class framework is documented in led-class.rst
within this documentation directory.

Each colored LED will be indexed under the multi_* files. The order of the
colors will be arbitrary. The multi_index file can be read to determine the
color name to indexed value.

The multi_index file is an array that contains the string list of the colors as
they are defined in each multi_* array file.

The multi_intensity is an array that can be read or written to for the
individual color intensities.  All elements within this array must be written in
order for the color LED intensities to be updated.

Directory Layout Example
========================
root:/sys/class/leds/multicolor:status# ls -lR
-rw-r--r--    1 root     root          4096 Oct 19 16:16 brightness
-r--r--r--    1 root     root          4096 Oct 19 16:16 max_brightness
-r--r--r--    1 root     root          4096 Oct 19 16:16 multi_index
-rw-r--r--    1 root     root          4096 Oct 19 16:16 multi_intensity

Multicolor Class Brightness Control
===================================
The brightness level for each LED is calculated based on the color LED
intensity setting divided by the global max_brightness setting multiplied by
the requested brightness.

led_brightness = brightness * multi_intensity/max_brightness

Example:
A user first writes the multi_intensity file with the brightness levels
for each LED that are necessary to achieve a certain color output from a
multicolor LED group.

cat /sys/class/leds/multicolor:status/multi_index
green blue red

echo 43 226 138 > /sys/class/leds/multicolor:status/multi_intensity

red -
	intensity = 138
	max_brightness = 255
green -
	intensity = 43
	max_brightness = 255
blue -
	intensity = 226
	max_brightness = 255

The user can control the brightness of that multicolor LED group by writing the
global 'brightness' control.  Assuming a max_brightness of 255 the user
may want to dim the LED color group to half.  The user would write a value of
128 to the global brightness file then the values written to each LED will be
adjusted base on this value.

cat /sys/class/leds/multicolor:status/max_brightness
255
echo 128 > /sys/class/leds/multicolor:status/brightness

adjusted_red_value = 128 * 138/255 = 69
adjusted_green_value = 128 * 43/255 = 21
adjusted_blue_value = 128 * 226/255 = 113

Reading the global brightness file will return the current brightness value of
the color LED group.

cat /sys/class/leds/multicolor:status/brightness
128


code:
========================
LED handling under Linux
========================

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

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

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

You can change triggers in a similar manner to the way an IO scheduler
is chosen (via /sys/class/leds/<device>/trigger). Trigger specific
parameters can appear in /sys/class/leds/<device> once a given trigger is
selected.

Design Philosophy
=================

The underlying design philosophy is simplicity. LEDs are simple devices
and the aim is to keep a small amount of code giving as much functionality
as 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, rather
        than to the hardware; the information related to the product and the bus
        to which given device is hooked is available in sysfs and can be
        retrieved using get_led_device_info.sh script from tools/leds; generally
        this section is expected mostly for LEDs that are somehow associated with
        other devices.

- color:
        one of LED_COLOR_ID_* definitions from the header
        include/dt-bindings/leds/common.h.

- function:
        one of LED_FUNCTION_* definitions from the header
        include/dt-bindings/leds/common.h.

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

It is possible that more than one LED with the same color and function will
be 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 use
function-enumerator property for that and then the concatenation will be handled
automatically by the LED core upon LED class device registration.

LED subsystem has also a protection against name clash, that may occur
when LED class device is created by a driver of hot-pluggable device and
it doesn't provide unique devicename section. In this case numerical
suffix (e.g. "_1", "_2", "_3" etc.) is added to the requested LED class
device name.

There might be still LED class drivers around using vendor or product name
for devicename, but this approach is now deprecated as it doesn't convey
any 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 name
meets the requirements pointed out here. It performs validation of the LED class
devicename sections and gives hints on expected value for a section in case
the validation fails for it. So far the script supports validation
of 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 as
individual led class attributes. As a solution which doesn't incur as much
overhead, I suggest these become part of the device name. The naming scheme
above leaves scope for further attributes should they be needed. If sections
of 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 stops
		blinking,

    - led_set_brightness_sync:
		for use cases when immediate effect is desired -
		it can block the caller for the time required for accessing
		device registers and can sleep, passing LED_OFF stops hardware
		blinking, 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_classdev struct and then call
`[devm_]led_classdev_register`. If the non devm version is used the driver
must call led_classdev_unregister from its remove function before
free-ing the led_classdev struct.

If the driver can detect hardware initiated brightness changes and thus
wants to have a brightness_hw_changed attribute then the LED_BRIGHT_HW_CHANGED
flag must be set in flags before registering. Calling
led_classdev_notify_brightness_hw_changed on a classdev not registered with
the 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. To
support this feature, a LED driver can optionally implement the
blink_set() function (see <linux/leds.h>). To set an LED to blinking,
however, it is better to use the API function led_blink_set(), as it
will check and implement software fallback if necessary.

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

The blink_set() function should choose a user friendly blinking value
if it is called with `*delay_on==0` && `*delay_off==0` parameters. In this
case the driver should give back the chosen value through delay_on and
delay_off parameters to the leds subsystem.

Setting the brightness to zero with brightness_set() callback function
should completely turn off the LED and cancel the previously programmed
hardware blinking function, if any.

Known Issues
============

The LED Trigger core cannot be a module as the simple trigger functions
would cause nightmare dependency issues. I see this as a minor issue
compared to the benefits the simple trigger functionality brings. The
rest of the LED subsystem can be modular.


code:
========================
Kernel driver for lm3556
========================

* Texas Instrument:
  1.5 A Synchronous Boost LED Flash Driver w/ High-Side Current Source
* Datasheet: http://www.national.com/ds/LM/LM3556.pdf

Authors:
      - Daniel Jeong

	Contact:Daniel Jeong(daniel.jeong-at-ti.com, gshark.jeong-at-gmail.com)

Description
-----------
There are 3 functions in LM3556, Flash, Torch and Indicator.

Flash Mode
^^^^^^^^^^

In Flash Mode, the LED current source(LED) provides 16 target current levels
from 93.75 mA to 1500 mA.The Flash currents are adjusted via the CURRENT
CONTROL REGISTER(0x09).Flash mode is activated by the ENABLE REGISTER(0x0A),
or by pulling the STROBE pin HIGH.

LM3556 Flash can be controlled through /sys/class/leds/flash/brightness file

* if STROBE pin is enabled, below example control brightness only, and
  ON / OFF will be controlled by STROBE pin.

Flash Example:

OFF::

	#echo 0 > /sys/class/leds/flash/brightness

93.75 mA::

	#echo 1 > /sys/class/leds/flash/brightness

...

1500  mA::

	#echo 16 > /sys/class/leds/flash/brightness

Torch Mode
^^^^^^^^^^

In Torch Mode, the current source(LED) is programmed via the CURRENT CONTROL
REGISTER(0x09).Torch Mode is activated by the ENABLE REGISTER(0x0A) or by the
hardware TORCH input.

LM3556 torch can be controlled through /sys/class/leds/torch/brightness file.
* if TORCH pin is enabled, below example control brightness only,
and ON / OFF will be controlled by TORCH pin.

Torch Example:

OFF::

	#echo 0 > /sys/class/leds/torch/brightness

46.88 mA::

	#echo 1 > /sys/class/leds/torch/brightness

...

375 mA::

	#echo 8 > /sys/class/leds/torch/brightness

Indicator Mode
^^^^^^^^^^^^^^

Indicator pattern can be set through /sys/class/leds/indicator/pattern file,
and 4 patterns are pre-defined in indicator_pattern array.

According to N-lank, Pulse time and N Period values, different pattern wiill
be generated.If you want new patterns for your own device, change
indicator_pattern array with your own values and INDIC_PATTERN_SIZE.

Please refer datasheet for more detail about N-Blank, Pulse time and N Period.

Indicator pattern example:

pattern 0::

	#echo 0 > /sys/class/leds/indicator/pattern

...

pattern 3::

	#echo 3 > /sys/class/leds/indicator/pattern

Indicator brightness can be controlled through
sys/class/leds/indicator/brightness file.

Example:

OFF::

	#echo 0 > /sys/class/leds/indicator/brightness

5.86 mA::

	#echo 1 > /sys/class/leds/indicator/brightness

...

46.875mA::

	#echo 8 > /sys/class/leds/indicator/brightness

Notes
-----
Driver expects it is registered using the i2c_board_info mechanism.
To register the chip at address 0x63 on specific adapter, set the platform data
according to include/linux/platform_data/leds-lm3556.h, set the i2c board info

Example::

	static struct i2c_board_info board_i2c_ch4[] __initdata = {
		{
			 I2C_BOARD_INFO(LM3556_NAME, 0x63),
			 .platform_data = &lm3556_pdata,
		 },
	};

and register it in the platform init function

Example::

	board_register_i2c_bus(4, 400,
				board_i2c_ch4, ARRAY_SIZE(board_i2c_ch4));


code:
====================
Kernel driver lp3944
====================

  * National Semiconductor LP3944 Fun-light Chip

    Prefix: 'lp3944'

    Addresses scanned: None (see the Notes section below)

    Datasheet:

	Publicly available at the National Semiconductor website
	http://www.national.com/pf/LP/LP3944.html

Authors:
	Antonio Ospite <ospite@studenti.unina.it>

Description
-----------
The LP3944 is a helper chip that can drive up to 8 leds, with two programmable
DIM modes; it could even be used as a gpio expander but this driver assumes it
is used as a led controller.

The DIM modes are used to set _blink_ patterns for leds, the pattern is
specified supplying two parameters:

  - period:
	from 0s to 1.6s
  - duty cycle:
	percentage of the period the led is on, from 0 to 100

Setting a led in DIM0 or DIM1 mode makes it blink according to the pattern.
See the datasheet for details.

LP3944 can be found on Motorola A910 smartphone, where it drives the rgb
leds, the camera flash light and the lcds power.

Notes
-----
The chip is used mainly in embedded contexts, so this driver expects it is
registered using the i2c_board_info mechanism.

To register the chip at address 0x60 on adapter 0, set the platform data
according to include/linux/leds-lp3944.h, set the i2c board info::

	static struct i2c_board_info a910_i2c_board_info[] __initdata = {
		{
			I2C_BOARD_INFO("lp3944", 0x60),
			.platform_data = &a910_lp3944_leds,
		},
	};

and register it in the platform init function::

	i2c_register_board_info(0, a910_i2c_board_info,
			ARRAY_SIZE(a910_i2c_board_info));


code:
========================
Kernel driver for lp5521
========================

* National Semiconductor LP5521 led driver chip
* Datasheet: http://www.national.com/pf/LP/LP5521.html

Authors: Mathias Nyman, Yuri Zaporozhets, Samu Onkalo

Contact: Samu Onkalo (samu.p.onkalo-at-nokia.com)

Description
-----------

LP5521 can drive up to 3 channels. Leds can be controlled directly via
the led class control interface. Channels have generic names:
lp5521:channelx, where x is 0 .. 2

All three channels can be also controlled using the engine micro programs.
More details of the instructions can be found from the public data sheet.

LP5521 has the internal program memory for running various LED patterns.
There are two ways to run LED patterns.

1) Legacy interface - enginex_mode and enginex_load
   Control interface for the engines:

   x is 1 .. 3

   enginex_mode:
	disabled, load, run
   enginex_load:
	store program (visible only in engine load mode)

  Example (start to blink the channel 2 led)::

	cd   /sys/class/leds/lp5521:channel2/device
	echo "load" > engine3_mode
	echo "037f4d0003ff6000" > engine3_load
	echo "run" > engine3_mode

  To stop the engine::

	echo "disabled" > engine3_mode

2) Firmware interface - LP55xx common interface

For the details, please refer to 'firmware' section in leds-lp55xx.txt

sysfs contains a selftest entry.

The test communicates with the chip and checks that
the clock mode is automatically set to the requested one.

Each channel has its own led current settings.

- /sys/class/leds/lp5521:channel0/led_current - RW
- /sys/class/leds/lp5521:channel0/max_current - RO

Format: 10x mA i.e 10 means 1.0 mA

example platform data::

  static struct lp55xx_led_config lp5521_led_config[] = {
	  {
		.name = "red",
		  .chan_nr        = 0,
		  .led_current    = 50,
		.max_current    = 130,
	  }, {
		.name = "green",
		  .chan_nr        = 1,
		  .led_current    = 0,
		.max_current    = 130,
	  }, {
		.name = "blue",
		  .chan_nr        = 2,
		  .led_current    = 0,
		.max_current    = 130,
	  }
  };

  static int lp5521_setup(void)
  {
	/* setup HW resources */
  }

  static void lp5521_release(void)
  {
	/* Release HW resources */
  }

  static void lp5521_enable(bool state)
  {
	/* Control of chip enable signal */
  }

  static struct lp55xx_platform_data lp5521_platform_data = {
	  .led_config     = lp5521_led_config,
	  .num_channels   = ARRAY_SIZE(lp5521_led_config),
	  .clock_mode     = LP55XX_CLOCK_EXT,
	  .setup_resources   = lp5521_setup,
	  .release_resources = lp5521_release,
	  .enable            = lp5521_enable,
  };

Note:
  chan_nr can have values between 0 and 2.
  The name of each channel can be configurable.
  If the name field is not defined, the default name will be set to 'xxxx:channelN'
  (XXXX : pdata->label or i2c client name, N : channel number)

If the current is set to 0 in the platform data, that channel is
disabled and it is not visible in the sysfs.


code:
========================
Kernel driver for lp5523
========================

* National Semiconductor LP5523 led driver chip
* Datasheet: http://www.national.com/pf/LP/LP5523.html

Authors: Mathias Nyman, Yuri Zaporozhets, Samu Onkalo
Contact: Samu Onkalo (samu.p.onkalo-at-nokia.com)

Description
-----------
LP5523 can drive up to 9 channels. Leds can be controlled directly via
the led class control interface.
The name of each channel is configurable in the platform data - name and label.
There are three options to make the channel name.

a) Define the 'name' in the platform data

To make specific channel name, then use 'name' platform data.

- /sys/class/leds/R1               (name: 'R1')
- /sys/class/leds/B1               (name: 'B1')

b) Use the 'label' with no 'name' field

For one device name with channel number, then use 'label'.
- /sys/class/leds/RGB:channelN     (label: 'RGB', N: 0 ~ 8)

c) Default

If both fields are NULL, 'lp5523' is used by default.
- /sys/class/leds/lp5523:channelN  (N: 0 ~ 8)

LP5523 has the internal program memory for running various LED patterns.
There are two ways to run LED patterns.

1) Legacy interface - enginex_mode, enginex_load and enginex_leds

  Control interface for the engines:

  x is 1 .. 3

  enginex_mode:
	disabled, load, run
  enginex_load:
	microcode load
  enginex_leds:
	led mux control

  ::

	cd /sys/class/leds/lp5523:channel2/device
	echo "load" > engine3_mode
	echo "9d80400004ff05ff437f0000" > engine3_load
	echo "111111111" > engine3_leds
	echo "run" > engine3_mode

  To stop the engine::

	echo "disabled" > engine3_mode

2) Firmware interface - LP55xx common interface

For the details, please refer to 'firmware' section in leds-lp55xx.txt

LP5523 has three master faders. If a channel is mapped to one of
the master faders, its output is dimmed based on the value of the master
fader.

For example::

  echo "123000123" > master_fader_leds

creates the following channel-fader mappings::

  channel 0,6 to master_fader1
  channel 1,7 to master_fader2
  channel 2,8 to master_fader3

Then, to have 25% of the original output on channel 0,6::

  echo 64 > master_fader1

To have 0% of the original output (i.e. no output) channel 1,7::

  echo 0 > master_fader2

To have 100% of the original output (i.e. no dimming) on channel 2,8::

  echo 255 > master_fader3

To clear all master fader controls::

  echo "000000000" > master_fader_leds

Selftest uses always the current from the platform data.

Each channel contains led current settings.
- /sys/class/leds/lp5523:channel2/led_current - RW
- /sys/class/leds/lp5523:channel2/max_current - RO

Format: 10x mA i.e 10 means 1.0 mA

Example platform data::

	static struct lp55xx_led_config lp5523_led_config[] = {
		{
			.name		= "D1",
			.chan_nr        = 0,
			.led_current    = 50,
			.max_current    = 130,
		},
	...
		{
			.chan_nr        = 8,
			.led_current    = 50,
			.max_current    = 130,
		}
	};

	static int lp5523_setup(void)
	{
		/* Setup HW resources */
	}

	static void lp5523_release(void)
	{
		/* Release HW resources */
	}

	static void lp5523_enable(bool state)
	{
		/* Control chip enable signal */
	}

	static struct lp55xx_platform_data lp5523_platform_data = {
		.led_config     = lp5523_led_config,
		.num_channels   = ARRAY_SIZE(lp5523_led_config),
		.clock_mode     = LP55XX_CLOCK_EXT,
		.setup_resources   = lp5523_setup,
		.release_resources = lp5523_release,
		.enable            = lp5523_enable,
	};

Note
  chan_nr can have values between 0 and 8.


code:
========================
Kernel driver for lp5562
========================

* TI LP5562 LED Driver

Author: Milo(Woogyom) Kim <milo.kim@ti.com>

Description
===========

  LP5562 can drive up to 4 channels. R/G/B and White.
  LEDs can be controlled directly via the led class control interface.

  All four channels can be also controlled using the engine micro programs.
  LP5562 has the internal program memory for running various LED patterns.
  For the details, please refer to 'firmware' section in leds-lp55xx.txt

Device attribute
================

engine_mux
  3 Engines are allocated in LP5562, but the number of channel is 4.
  Therefore each channel should be mapped to the engine number.

  Value: RGB or W

  This attribute is used for programming LED data with the firmware interface.
  Unlike the LP5521/LP5523/55231, LP5562 has unique feature for the engine mux,
  so additional sysfs is required

  LED Map

  ===== === ===============================
  Red   ... Engine 1 (fixed)
  Green ... Engine 2 (fixed)
  Blue  ... Engine 3 (fixed)
  White ... Engine 1 or 2 or 3 (selective)
  ===== === ===============================

How to load the program data using engine_mux
=============================================

  Before loading the LP5562 program data, engine_mux should be written between
  the engine selection and loading the firmware.
  Engine mux has two different mode, RGB and W.
  RGB is used for loading RGB program data, W is used for W program data.

  For example, run blinking green channel pattern::

    echo 2 > /sys/bus/i2c/devices/xxxx/select_engine     # 2 is for green channel
    echo "RGB" > /sys/bus/i2c/devices/xxxx/engine_mux    # engine mux for RGB
    echo 1 > /sys/class/firmware/lp5562/loading
    echo "4000600040FF6000" > /sys/class/firmware/lp5562/data
    echo 0 > /sys/class/firmware/lp5562/loading
    echo 1 > /sys/bus/i2c/devices/xxxx/run_engine

  To run a blinking white pattern::

    echo 1 or 2 or 3 > /sys/bus/i2c/devices/xxxx/select_engine
    echo "W" > /sys/bus/i2c/devices/xxxx/engine_mux
    echo 1 > /sys/class/firmware/lp5562/loading
    echo "4000600040FF6000" > /sys/class/firmware/lp5562/data
    echo 0 > /sys/class/firmware/lp5562/loading
    echo 1 > /sys/bus/i2c/devices/xxxx/run_engine

How to load the predefined patterns
===================================

  Please refer to 'leds-lp55xx.txt"

Setting Current of Each Channel
===============================

  Like LP5521 and LP5523/55231, LP5562 provides LED current settings.
  The 'led_current' and 'max_current' are used.

Example of Platform data
========================

::

	static struct lp55xx_led_config lp5562_led_config[] = {
		{
			.name 		= "R",
			.chan_nr	= 0,
			.led_current	= 20,
			.max_current	= 40,
		},
		{
			.name 		= "G",
			.chan_nr	= 1,
			.led_current	= 20,
			.max_current	= 40,
		},
		{
			.name 		= "B",
			.chan_nr	= 2,
			.led_current	= 20,
			.max_current	= 40,
		},
		{
			.name 		= "W",
			.chan_nr	= 3,
			.led_current	= 20,
			.max_current	= 40,
		},
	};

	static int lp5562_setup(void)
	{
		/* setup HW resources */
	}

	static void lp5562_release(void)
	{
		/* Release HW resources */
	}

	static void lp5562_enable(bool state)
	{
		/* Control of chip enable signal */
	}

	static struct lp55xx_platform_data lp5562_platform_data = {
		.led_config     = lp5562_led_config,
		.num_channels   = ARRAY_SIZE(lp5562_led_config),
		.setup_resources   = lp5562_setup,
		.release_resources = lp5562_release,
		.enable            = lp5562_enable,
	};

To configure the platform specific data, lp55xx_platform_data structure is used

If the current is set to 0 in the platform data, that channel is
disabled and it is not visible in the sysfs.


code:
=================================================
LP5521/LP5523/LP55231/LP5562/LP8501 Common Driver
=================================================

Authors: Milo(Woogyom) Kim <milo.kim@ti.com>

Description
-----------
LP5521, LP5523/55231, LP5562 and LP8501 have common features as below.

  Register access via the I2C
  Device initialization/deinitialization
  Create LED class devices for multiple output channels
  Device attributes for user-space interface
  Program memory for running LED patterns

The LP55xx common driver provides these features using exported functions.

  lp55xx_init_device() / lp55xx_deinit_device()
  lp55xx_register_leds() / lp55xx_unregister_leds()
  lp55xx_regsister_sysfs() / lp55xx_unregister_sysfs()

( Driver Structure Data )

In lp55xx common driver, two different data structure is used.

* lp55xx_led
    control multi output LED channels such as led current, channel index.
* lp55xx_chip
    general chip control such like the I2C and platform data.

For example, LP5521 has maximum 3 LED channels.
LP5523/55231 has 9 output channels::

  lp55xx_chip for LP5521 ... lp55xx_led #1
			     lp55xx_led #2
			     lp55xx_led #3

  lp55xx_chip for LP5523 ... lp55xx_led #1
			     lp55xx_led #2
				   .
				   .
			     lp55xx_led #9

( Chip Dependent Code )

To support device specific configurations, special structure
'lpxx_device_config' is used.

  - Maximum number of channels
  - Reset command, chip enable command
  - Chip specific initialization
  - Brightness control register access
  - Setting LED output current
  - Program memory address access for running patterns
  - Additional device specific attributes

( Firmware Interface )

LP55xx family devices have the internal program memory for running
various LED patterns.

This pattern data is saved as a file in the user-land or
hex byte string is written into the memory through the I2C.

LP55xx common driver supports the firmware interface.

LP55xx chips have three program engines.

To load and run the pattern, the programming sequence is following.

  (1) Select an engine number (1/2/3)
  (2) Mode change to load
  (3) Write pattern data into selected area
  (4) Mode change to run

The LP55xx common driver provides simple interfaces as below.

select_engine:
	Select which engine is used for running program
run_engine:
	Start program which is loaded via the firmware interface
firmware:
	Load program data

In case of LP5523, one more command is required, 'enginex_leds'.
It is used for selecting LED output(s) at each engine number.
In more details, please refer to 'leds-lp5523.txt'.

For example, run blinking pattern in engine #1 of LP5521::

	echo 1 > /sys/bus/i2c/devices/xxxx/select_engine
	echo 1 > /sys/class/firmware/lp5521/loading
	echo "4000600040FF6000" > /sys/class/firmware/lp5521/data
	echo 0 > /sys/class/firmware/lp5521/loading
	echo 1 > /sys/bus/i2c/devices/xxxx/run_engine

For example, run blinking pattern in engine #3 of LP55231

Two LEDs are configured as pattern output channels::

	echo 3 > /sys/bus/i2c/devices/xxxx/select_engine
	echo 1 > /sys/class/firmware/lp55231/loading
	echo "9d0740ff7e0040007e00a0010000" > /sys/class/firmware/lp55231/data
	echo 0 > /sys/class/firmware/lp55231/loading
	echo "000001100" > /sys/bus/i2c/devices/xxxx/engine3_leds
	echo 1 > /sys/bus/i2c/devices/xxxx/run_engine

To start blinking patterns in engine #2 and #3 simultaneously::

	for idx in 2 3
	do
	echo $idx > /sys/class/leds/red/device/select_engine
	sleep 0.1
	echo 1 > /sys/class/firmware/lp5521/loading
	echo "4000600040FF6000" > /sys/class/firmware/lp5521/data
	echo 0 > /sys/class/firmware/lp5521/loading
	done
	echo 1 > /sys/class/leds/red/device/run_engine

Here is another example for LP5523.

Full LED strings are selected by 'engine2_leds'::

	echo 2 > /sys/bus/i2c/devices/xxxx/select_engine
	echo 1 > /sys/class/firmware/lp5523/loading
	echo "9d80400004ff05ff437f0000" > /sys/class/firmware/lp5523/data
	echo 0 > /sys/class/firmware/lp5523/loading
	echo "111111111" > /sys/bus/i2c/devices/xxxx/engine2_leds
	echo 1 > /sys/bus/i2c/devices/xxxx/run_engine

As soon as 'loading' is set to 0, registered callback is called.
Inside the callback, the selected engine is loaded and memory is updated.
To run programmed pattern, 'run_engine' attribute should be enabled.

The pattern sequence of LP8501 is similar to LP5523.

However pattern data is specific.

Ex 1) Engine 1 is used::

	echo 1 > /sys/bus/i2c/devices/xxxx/select_engine
	echo 1 > /sys/class/firmware/lp8501/loading
	echo "9d0140ff7e0040007e00a001c000" > /sys/class/firmware/lp8501/data
	echo 0 > /sys/class/firmware/lp8501/loading
	echo 1 > /sys/bus/i2c/devices/xxxx/run_engine

Ex 2) Engine 2 and 3 are used at the same time::

	echo 2 > /sys/bus/i2c/devices/xxxx/select_engine
	sleep 1
	echo 1 > /sys/class/firmware/lp8501/loading
	echo "9d0140ff7e0040007e00a001c000" > /sys/class/firmware/lp8501/data
	echo 0 > /sys/class/firmware/lp8501/loading
	sleep 1
	echo 3 > /sys/bus/i2c/devices/xxxx/select_engine
	sleep 1
	echo 1 > /sys/class/firmware/lp8501/loading
	echo "9d0340ff7e0040007e00a001c000" > /sys/class/firmware/lp8501/data
	echo 0 > /sys/class/firmware/lp8501/loading
	sleep 1
	echo 1 > /sys/class/leds/d1/device/run_engine

( 'run_engine' and 'firmware_cb' )

The sequence of running the program data is common.

But each device has own specific register addresses for commands.

To support this, 'run_engine' and 'firmware_cb' are configurable in each driver.

run_engine:
	Control the selected engine
firmware_cb:
	The callback function after loading the firmware is done.

	Chip specific commands for loading and updating program memory.

( Predefined pattern data )

Without the firmware interface, LP55xx driver provides another method for
loading a LED pattern. That is 'predefined' pattern.

A predefined pattern is defined in the platform data and load it(or them)
via the sysfs if needed.

To use the predefined pattern concept, 'patterns' and 'num_patterns' should be
configured.

Example of predefined pattern data::

  /* mode_1: blinking data */
  static const u8 mode_1[] = {
		0x40, 0x00, 0x60, 0x00, 0x40, 0xFF, 0x60, 0x00,
		};

  /* mode_2: always on */
  static const u8 mode_2[] = { 0x40, 0xFF, };

  struct lp55xx_predef_pattern board_led_patterns[] = {
	{
		.r = mode_1,
		.size_r = ARRAY_SIZE(mode_1),
	},
	{
		.b = mode_2,
		.size_b = ARRAY_SIZE(mode_2),
	},
  }

  struct lp55xx_platform_data lp5562_pdata = {
  ...
	.patterns      = board_led_patterns,
	.num_patterns  = ARRAY_SIZE(board_led_patterns),
  };

Then, mode_1 and mode_2 can be run via through the sysfs::

  echo 1 > /sys/bus/i2c/devices/xxxx/led_pattern    # red blinking LED pattern
  echo 2 > /sys/bus/i2c/devices/xxxx/led_pattern    # blue LED always on

To stop running pattern::

  echo 0 > /sys/bus/i2c/devices/xxxx/led_pattern


code:
=======================================
Kernel driver for Mellanox systems LEDs
=======================================

Provide system LED support for the nex Mellanox systems:
"msx6710", "msx6720", "msb7700", "msn2700", "msx1410",
"msn2410", "msb7800", "msn2740", "msn2100".

Description
-----------
Driver provides the following LEDs for the systems "msx6710", "msx6720",
"msb7700", "msn2700", "msx1410", "msn2410", "msb7800", "msn2740":

  - mlxcpld:fan1:green
  - mlxcpld:fan1:red
  - mlxcpld:fan2:green
  - mlxcpld:fan2:red
  - mlxcpld:fan3:green
  - mlxcpld:fan3:red
  - mlxcpld:fan4:green
  - mlxcpld:fan4:red
  - mlxcpld:psu:green
  - mlxcpld:psu:red
  - mlxcpld:status:green
  - mlxcpld:status:red

 "status"
  - CPLD reg offset: 0x20
  - Bits [3:0]

 "psu"
  - CPLD reg offset: 0x20
  - Bits [7:4]

 "fan1"
  - CPLD reg offset: 0x21
  - Bits [3:0]

 "fan2"
  - CPLD reg offset: 0x21
  - Bits [7:4]

 "fan3"
  - CPLD reg offset: 0x22
  - Bits [3:0]

 "fan4"
  - CPLD reg offset: 0x22
  - Bits [7:4]

 Color mask for all the above LEDs:

  [bit3,bit2,bit1,bit0] or
  [bit7,bit6,bit5,bit4]:

	- [0,0,0,0] = LED OFF
	- [0,1,0,1] = Red static ON
	- [1,1,0,1] = Green static ON
	- [0,1,1,0] = Red blink 3Hz
	- [1,1,1,0] = Green blink 3Hz
	- [0,1,1,1] = Red blink 6Hz
	- [1,1,1,1] = Green blink 6Hz

Driver provides the following LEDs for the system "msn2100":

  - mlxcpld:fan:green
  - mlxcpld:fan:red
  - mlxcpld:psu1:green
  - mlxcpld:psu1:red
  - mlxcpld:psu2:green
  - mlxcpld:psu2:red
  - mlxcpld:status:green
  - mlxcpld:status:red
  - mlxcpld:uid:blue

 "status"
  - CPLD reg offset: 0x20
  - Bits [3:0]

 "fan"
  - CPLD reg offset: 0x21
  - Bits [3:0]

 "psu1"
  - CPLD reg offset: 0x23
  - Bits [3:0]

 "psu2"
  - CPLD reg offset: 0x23
  - Bits [7:4]

 "uid"
  - CPLD reg offset: 0x24
  - Bits [3:0]

 Color mask for all the above LEDs, excepted uid:

  [bit3,bit2,bit1,bit0] or
  [bit7,bit6,bit5,bit4]:

	- [0,0,0,0] = LED OFF
	- [0,1,0,1] = Red static ON
	- [1,1,0,1] = Green static ON
	- [0,1,1,0] = Red blink 3Hz
	- [1,1,1,0] = Green blink 3Hz
	- [0,1,1,1] = Red blink 6Hz
	- [1,1,1,1] = Green blink 6Hz

 Color mask for uid LED:
  [bit3,bit2,bit1,bit0]:

	- [0,0,0,0] = LED OFF
	- [1,1,0,1] = Blue static ON
	- [1,1,1,0] = Blue blink 3Hz
	- [1,1,1,1] = Blue blink 6Hz

Driver supports HW blinking at 3Hz and 6Hz frequency (50% duty cycle).
For 3Hz duty cylce is about 167 msec, for 6Hz is about 83 msec.


code:
.. SPDX-License-Identifier: GPL-2.0

==============================
Kernel driver for Qualcomm LPG
==============================

Description
-----------

The Qualcomm LPG can be found in a variety of Qualcomm PMICs and consists of a
number of PWM channels, a programmable pattern lookup table and a RGB LED
current sink.

To facilitate the various use cases, the LPG channels can be exposed as
individual LEDs, grouped together as RGB LEDs or otherwise be accessed as PWM
channels. The output of each PWM channel is routed to other hardware
blocks, such as the RGB current sink, GPIO pins etc.

The each PWM channel can operate with a period between 27us and 384 seconds and
has a 9 bit resolution of the duty cycle.

In order to provide support for status notifications with the CPU subsystem in
deeper idle states the LPG provides pattern support. This consists of a shared
lookup table of brightness values and per channel properties to select the
range within the table to use, the rate and if the pattern should repeat.

The pattern for a channel can be programmed using the "pattern" trigger, using
the hw_pattern attribute.

/sys/class/leds/<led>/hw_pattern
--------------------------------

Specify a hardware pattern for a Qualcomm LPG LED.

The pattern is a series of brightness and hold-time pairs, with the hold-time
expressed in milliseconds. The hold time is a property of the pattern and must
therefor be identical for each element in the pattern (except for the pauses
described below). As the LPG hardware is not able to perform the linear
transitions expected by the leds-trigger-pattern format, each entry in the
pattern must be followed a zero-length entry of the same brightness.

Simple pattern::

    "255 500 255 0 0 500 0 0"

        ^
        |
    255 +----+    +----+
        |    |    |    |      ...
      0 |    +----+    +----
        +---------------------->
        0    5   10   15     time (100ms)

The LPG supports specifying a longer hold-time for the first and last element
in the pattern, the so called "low pause" and "high pause".

Low-pause pattern::

    "255 1000 255 0 0 500 0 0 255 500 255 0 0 500 0 0"

        ^
        |
    255 +--------+    +----+    +----+    +--------+
        |        |    |    |    |    |    |        |      ...
      0 |        +----+    +----+    +----+        +----
        +----------------------------->
        0    5   10   15  20   25   time (100ms)

Similarily, the last entry can be stretched by using a higher hold-time on the
last entry.

In order to save space in the shared lookup table the LPG supports "ping-pong"
mode, in which case each run through the pattern is performed by first running
the pattern forward, then backwards. This mode is automatically used by the
driver when the given pattern is a palindrome. In this case the "high pause"
denotes the wait time before the pattern is run in reverse and as such the
specified hold-time of the middle item in the pattern is allowed to have a
different hold-time.


code:
.. SPDX-License-Identifier: GPL-2.0

===================================
Kernel driver for Spreadtrum SC27XX
===================================

/sys/class/leds/<led>/hw_pattern
--------------------------------

Specify a hardware pattern for the SC27XX LED. For the SC27XX
LED controller, it only supports 4 stages to make a single
hardware pattern, which is used to configure the rise time,
high time, fall time and low time for the breathing mode.

For the breathing mode, the SC27XX LED only expects one brightness
for the high stage. To be compatible with the hardware pattern
format, we should set brightness as 0 for rise stage, fall
stage and low stage.

- Min stage duration: 125 ms
- Max stage duration: 31875 ms

Since the stage duration step is 125 ms, the duration should be
a multiplier of 125, like 125ms, 250ms, 375ms, 500ms ... 31875ms.

Thus the format of the hardware pattern values should be:
"0 rise_duration brightness high_duration 0 fall_duration 0 low_duration".


code:
====================
One-shot LED Trigger
====================

This is a LED trigger useful for signaling the user of an event where there are
no clear trap points to put standard led-on and led-off settings.  Using this
trigger, the application needs only to signal the trigger when an event has
happened, than the trigger turns the LED on and than keeps it off for a
specified amount of time.

This trigger is meant to be usable both for sporadic and dense events.  In the
first case, the trigger produces a clear single controlled blink for each
event, while in the latter it keeps blinking at constant rate, as to signal
that the events are arriving continuously.

A one-shot LED only stays in a constant state when there are no events.  An
additional "invert" property specifies if the LED has to stay off (normal) or
on (inverted) when not rearmed.

The trigger can be activated from user space on led class devices as shown
below::

  echo oneshot > trigger

This adds sysfs attributes to the LED that are documented in:
Documentation/ABI/testing/sysfs-class-led-trigger-oneshot

Example use-case: network devices, initialization::

  echo oneshot > trigger # set trigger for this led
  echo 33 > delay_on     # blink at 1 / (33 + 33) Hz on continuous traffic
  echo 33 > delay_off

interface goes up::

  echo 1 > invert # set led as normally-on, turn the led on

packet received/transmitted::

  echo 1 > shot # led starts blinking, ignored if already blinking

interface goes down::

  echo 0 > invert # set led as normally-off, turn the led off


code:
=====================
LED Transient Trigger
=====================

The leds timer trigger does not currently have an interface to activate
a one shot timer. The current support allows for setting two timers, one for
specifying how long a state to be on, and the second for how long the state
to be off. The delay_on value specifies the time period an LED should stay
in on state, followed by a delay_off value that specifies how long the LED
should stay in off state. The on and off cycle repeats until the trigger
gets deactivated. There is no provision for one time activation to implement
features that require an on or off state to be held just once and then stay in
the original state forever.

Without one shot timer interface, user space can still use timer trigger to
set a timer to hold a state, however when user space application crashes or
goes away without deactivating the timer, the hardware will be left in that
state permanently.

Transient trigger addresses the need for one shot timer activation. The
transient trigger can be enabled and disabled just like the other leds
triggers.

When an led class device driver registers itself, it can specify all leds
triggers it supports and a default trigger. During registration, activation
routine for the default trigger gets called. During registration of an led
class device, the LED state does not change.

When the driver unregisters, deactivation routine for the currently active
trigger will be called, and LED state is changed to LED_OFF.

Driver suspend changes the LED state to LED_OFF and resume doesn't change
the state. Please note that there is no explicit interaction between the
suspend and resume actions and the currently enabled trigger. LED state
changes are suspended while the driver is in suspend state. Any timers
that are active at the time driver gets suspended, continue to run, without
being able to actually change the LED state. Once driver is resumed, triggers
start functioning again.

LED state changes are controlled using brightness which is a common led
class device property. When brightness is set to 0 from user space via
echo 0 > brightness, it will result in deactivating the current trigger.

Transient trigger uses standard register and unregister interfaces. During
trigger registration, for each led class device that specifies this trigger
as its default trigger, trigger activation routine will get called. During
registration, the LED state does not change, unless there is another trigger
active, in which case LED state changes to LED_OFF.

During trigger unregistration, LED state gets changed to LED_OFF.

Transient trigger activation routine doesn't change the LED state. It
creates its properties and does its initialization. Transient trigger
deactivation routine, will cancel any timer that is active before it cleans
up and removes the properties it created. It will restore the LED state to
non-transient state. When driver gets suspended, irrespective of the transient
state, the LED state changes to LED_OFF.

Transient trigger can be enabled and disabled from user space on led class
devices, that support this trigger as shown below::

	echo transient > trigger
	echo none > trigger

NOTE:
	Add a new property trigger state to control the state.

This trigger exports three properties, activate, state, and duration. When
transient trigger is activated these properties are set to default values.

- duration allows setting timer value in msecs. The initial value is 0.
- activate allows activating and deactivating the timer specified by
  duration as needed. The initial and default value is 0.  This will allow
  duration to be set after trigger activation.
- state allows user to specify a transient state to be held for the specified
  duration.

	activate
	      - one shot timer activate mechanism.
		1 when activated, 0 when deactivated.
		default value is zero when transient trigger is enabled,
		to allow duration to be set.

		activate state indicates a timer with a value of specified
		duration running.
		deactivated state indicates that there is no active timer
		running.

	duration
	      - one shot timer value. When activate is set, duration value
		is used to start a timer that runs once. This value doesn't
		get changed by the trigger unless user does a set via
		echo new_value > duration

	state
	      - transient state to be held. It has two values 0 or 1. 0 maps
		to LED_OFF and 1 maps to LED_FULL. The specified state is
		held for the duration of the one shot timer and then the
		state gets changed to the non-transient state which is the
		inverse of transient state.
		If state = LED_FULL, when the timer runs out the state will
		go back to LED_OFF.
		If state = LED_OFF, when the timer runs out the state will
		go back to LED_FULL.
		Please note that current LED state is not checked prior to
		changing the state to the specified state.
		Driver could map these values to inverted depending on the
		default states it defines for the LED in its brightness_set()
		interface which is called from the led brightness_set()
		interfaces to control the LED state.

When timer expires activate goes back to deactivated state, duration is left
at the set value to be used when activate is set at a future time. This will
allow user app to set the time once and activate it to run it once for the
specified value as needed. When timer expires, state is restored to the
non-transient state which is the inverse of the transient state:

	=================   ===============================================
	echo 1 > activate   starts timer = duration when duration is not 0.
	echo 0 > activate   cancels currently running timer.
	echo n > duration   stores timer value to be used upon next
			    activate. Currently active timer if
			    any, continues to run for the specified time.
	echo 0 > duration   stores timer value to be used upon next
			    activate. Currently active timer if any,
			    continues to run for the specified time.
	echo 1 > state      stores desired transient state LED_FULL to be
			    held for the specified duration.
	echo 0 > state      stores desired transient state LED_OFF to be
			    held for the specified duration.
	=================   ===============================================

What is not supported
=====================

- Timer activation is one shot and extending and/or shortening the timer
  is not supported.

Examples
========

use-case 1::

	echo transient > trigger
	echo n > duration
	echo 1 > state

repeat the following step as needed::

	echo 1 > activate - start timer = duration to run once
	echo 1 > activate - start timer = duration to run once
	echo none > trigger

This trigger is intended to be used for the following example use cases:

 - Use of LED by user space app as activity indicator.
 - Use of LED by user space app as a kind of watchdog indicator -- as
   long as the app is alive, it can keep the LED illuminated, if it dies
   the LED will be extinguished automatically.
 - Use by any user space app that needs a transient GPIO output.


code:
====================
USB port LED trigger
====================

This LED trigger can be used for signalling to the user a presence of USB device
in a given port. It simply turns on LED when device appears and turns it off
when it disappears.

It requires selecting USB ports that should be observed. All available ones are
listed as separated entries in a "ports" subdirectory. Selecting is handled by
echoing "1" to a chosen port.

Please note that this trigger allows selecting multiple USB ports for a single
LED.

This can be useful in two cases:

1) Device with single USB LED and few physical ports
====================================================

In such a case LED will be turned on as long as there is at least one connected
USB device.

2) Device with a physical port handled by few controllers
=========================================================

Some devices may have one controller per PHY standard. E.g. USB 3.0 physical
port may be handled by ohci-platform, ehci-platform and xhci-hcd. If there is
only one LED user will most likely want to assign ports from all 3 hubs.

This trigger can be activated from user space on led class devices as shown
below::

  echo usbport > trigger

This adds sysfs attributes to the LED that are documented in:
Documentation/ABI/testing/sysfs-class-led-trigger-usbport

Example use-case::

  echo usbport > trigger
  echo 1 > ports/usb1-port1
  echo 1 > ports/usb2-port1
  cat ports/usb1-port1
  echo 0 > ports/usb1-port1


code:
==============
Userspace LEDs
==============

The uleds driver supports userspace LEDs. This can be useful for testing
triggers and can also be used to implement virtual LEDs.

Usage
=====

When the driver is loaded, a character device is created at /dev/uleds. To
create a new LED class device, open /dev/uleds and write a uleds_user_dev
structure to it (found in kernel public header file linux/uleds.h)::

    #define LED_MAX_NAME_SIZE 64

    struct uleds_user_dev {
	char name[LED_MAX_NAME_SIZE];
    };

A new LED class device will be created with the name given. The name can be
any valid sysfs device node name, but consider using the LED class naming
convention of "devicename:color:function".

The current brightness is found by reading a single byte from the character
device. Values are unsigned: 0 to 255. Reading will block until the brightness
changes. The device node can also be polled to notify when the brightness value
changes.

The LED class device will be removed when the open file handle to /dev/uleds
is closed.

Multiple LED class devices are created by opening additional file handles to
/dev/uleds.

See tools/leds/uledmon.c for an example userspace program.


code:
-*- org -*-

It is somehow important to provide consistent interface to the
userland. LED devices have one problem there, and that is naming of
directories in /sys/class/leds. It would be nice if userland would
just know right "name" for given LED function, but situation got more
complex.

Anyway, if backwards compatibility is not an issue, new code should
use one of the "good" names from this list, and you should extend the
list where applicable.

Legacy names are listed, too; in case you are writing application that
wants to use particular feature, you should probe for good name, first,
but then try the legacy ones, too.

Notice there's a list of functions in include/dt-bindings/leds/common.h .

* Gamepads and joysticks

Game controllers may feature LEDs to indicate a player number. This is commonly
used on game consoles in which multiple controllers can be connected to a system.
The "player LEDs" are then programmed with a pattern to indicate a particular
player. For example, a game controller with 4 LEDs, may be programmed with "x---"
to indicate player 1, "-x--" to indicate player 2 etcetera where "x" means on.
Input drivers can utilize the LED class to expose the individual player LEDs
of a game controller using the function "player".
Note: tracking and management of Player IDs is the responsibility of user space,
though drivers may pick a default value.

Good: "input*:*:player-{1,2,3,4,5}

* Keyboards

Good: "input*:*:capslock"
Good: "input*:*:scrolllock"
Good: "input*:*:numlock"
Legacy: "shift-key-light" (Motorola Droid 4, capslock)

Set of common keyboard LEDs, going back to PC AT or so.

Legacy: "tpacpi::thinklight" (IBM/Lenovo Thinkpads)
Legacy: "lp5523:kb{1,2,3,4,5,6}" (Nokia N900)

Frontlight/backlight of main keyboard.

Legacy: "button-backlight" (Motorola Droid 4)

Some phones have touch buttons below screen; it is different from main
keyboard. And this is their backlight.

* Sound subsystem

Good: "platform:*:mute"
Good: "platform:*:micmute"

LEDs on notebook body, indicating that sound input / output is muted.

* System notification

Legacy: "status-led:{red,green,blue}" (Motorola Droid 4)
Legacy: "lp5523:{r,g,b}" (Nokia N900)

Phones usually have multi-color status LED.

* Power management

Good: "platform:*:charging" (allwinner sun50i)

* Screen

Good: ":backlight" (Motorola Droid 4)


code:
============
LITMUS TESTS
============

Each subdirectory contains litmus tests that are typical to describe the
semantics of respective kernel APIs.
For more information about how to "run" a litmus test or how to generate
a kernel test module based on a litmus test, please see
tools/memory-model/README.

atomic (/atomic derectory)
--------------------------

Atomic-RMW+mb__after_atomic-is-stronger-than-acquire.litmus
    Test that an atomic RMW followed by a smp_mb__after_atomic() is
    stronger than a normal acquire: both the read and write parts of
    the RMW are ordered before the subsequential memory accesses.

Atomic-RMW-ops-are-atomic-WRT-atomic_set.litmus
    Test that atomic_set() cannot break the atomicity of atomic RMWs.
    NOTE: Require herd7 7.56 or later which supports "(void)expr".

RCU (/rcu directory)
--------------------

MP+onceassign+derefonce.litmus (under tools/memory-model/litmus-tests/)
    Demonstrates the use of rcu_assign_pointer() and rcu_dereference() to
    ensure that an RCU reader will not see pre-initialization garbage.

RCU+sync+read.litmus
RCU+sync+free.litmus
    Both the above litmus tests demonstrate the RCU grace period guarantee
    that an RCU read-side critical section can never span a grace period.

path: Documentation/litmus-tests/README


code:
C Atomic-RMW+mb__after_atomic-is-stronger-than-acquire

(*
 * Result: Never
 *
 * Test that an atomic RMW followed by a smp_mb__after_atomic() is
 * stronger than a normal acquire: both the read and write parts of
 * the RMW are ordered before the subsequential memory accesses.
 *)

{
}

P0(int *x, atomic_t *y)
{
	int r0;
	int r1;

	r0 = READ_ONCE(*x);
	smp_rmb();
	r1 = atomic_read(y);
}

P1(int *x, atomic_t *y)
{
	atomic_inc(y);
	smp_mb__after_atomic();
	WRITE_ONCE(*x, 1);
}

exists
(0:r0=1 /\ 0:r1=0)


code:
C Atomic-RMW-ops-are-atomic-WRT-atomic_set

(*
 * Result: Never
 *
 * Test that atomic_set() cannot break the atomicity of atomic RMWs.
 * NOTE: This requires herd7 7.56 or later which supports "(void)expr".
 *)

{
	atomic_t v = ATOMIC_INIT(1);
}

P0(atomic_t *v)
{
	(void)atomic_add_unless(v, 1, 0);
}

P1(atomic_t *v)
{
	atomic_set(v, 0);
}

exists
(v=2)


code:
C RCU+sync+free

(*
 * Result: Never
 *
 * This litmus test demonstrates that an RCU reader can never see a write that
 * follows a grace period, if it did not see writes that precede that grace
 * period.
 *
 * This is a typical pattern of RCU usage, where the write before the grace
 * period assigns a pointer, and the writes following the grace period destroy
 * the object that the pointer used to point to.
 *
 * This is one implication of the RCU grace-period guarantee, which says (among
 * other things) that an RCU read-side critical section cannot span a grace period.
 *)

{
int x = 1;
int *y = &x;
int z = 1;
}

P0(int *x, int *z, int **y)
{
	int *r0;
	int r1;

	rcu_read_lock();
	r0 = rcu_dereference(*y);
	r1 = READ_ONCE(*r0);
	rcu_read_unlock();
}

P1(int *x, int *z, int **y)
{
	rcu_assign_pointer(*y, z);
	synchronize_rcu();
	WRITE_ONCE(*x, 0);
}

exists (0:r0=x /\ 0:r1=0)


code:
C RCU+sync+read

(*
 * Result: Never
 *
 * This litmus test demonstrates that after a grace period, an RCU updater always
 * sees all stores done in prior RCU read-side critical sections. Such
 * read-side critical sections would have ended before the grace period ended.
 *
 * This is one implication of the RCU grace-period guarantee, which says (among
 * other things) that an RCU read-side critical section cannot span a grace period.
 *)

{
int x = 0;
int y = 0;
}

P0(int *x, int *y)
{
	rcu_read_lock();
	WRITE_ONCE(*x, 1);
	WRITE_ONCE(*y, 1);
	rcu_read_unlock();
}

P1(int *x, int *y)
{
	int r0;
	int r1;

	r0 = READ_ONCE(*x);
	synchronize_rcu();
	r1 = READ_ONCE(*y);
}

exists (1:r0=1 /\ 1:r1=0)


code:
.. SPDX-License-Identifier: GPL-2.0

=================
Livepatching APIs
=================

Livepatch Enablement
====================

.. kernel-doc:: kernel/livepatch/core.c
   :export:

Shadow Variables
================

.. kernel-doc:: kernel/livepatch/shadow.c
   :export:

System State Changes
====================

.. kernel-doc:: kernel/livepatch/state.c
   :export:

Object Types
============

.. kernel-doc:: include/linux/livepatch.h
   :identifiers: klp_patch klp_object klp_func klp_callbacks klp_state


code:
======================
(Un)patching Callbacks
======================

Livepatch (un)patch-callbacks provide a mechanism for livepatch modules
to execute callback functions when a kernel object is (un)patched.  They
can be considered a **power feature** that **extends livepatching abilities**
to include:

  - Safe updates to global data

  - "Patches" to init and probe functions

  - Patching otherwise unpatchable code (i.e. assembly)

In most cases, (un)patch callbacks will need to be used in conjunction
with memory barriers and kernel synchronization primitives, like
mutexes/spinlocks, or even stop_machine(), to avoid concurrency issues.

1. Motivation
=============

Callbacks differ from existing kernel facilities:

  - Module init/exit code doesn't run when disabling and re-enabling a
    patch.

  - A module notifier can't stop a to-be-patched module from loading.

Callbacks are part of the klp_object structure and their implementation
is specific to that klp_object.  Other livepatch objects may or may not
be patched, irrespective of the target klp_object's current state.

2. Callback types
=================

Callbacks can be registered for the following livepatch actions:

  * Pre-patch
                 - before a klp_object is patched

  * Post-patch
                 - after a klp_object has been patched and is active
                   across all tasks

  * Pre-unpatch
                 - before a klp_object is unpatched (ie, patched code is
                   active), used to clean up post-patch callback
                   resources

  * Post-unpatch
                 - after a klp_object has been patched, all code has
                   been restored and no tasks are running patched code,
                   used to cleanup pre-patch callback resources

3. How it works
===============

Each callback is optional, omitting one does not preclude specifying any
other.  However, the livepatching core executes the handlers in
symmetry: pre-patch callbacks have a post-unpatch counterpart and
post-patch callbacks have a pre-unpatch counterpart.  An unpatch
callback will only be executed if its corresponding patch callback was
executed.  Typical use cases pair a patch handler that acquires and
configures resources with an unpatch handler tears down and releases
those same resources.

A callback is only executed if its host klp_object is loaded.  For
in-kernel vmlinux targets, this means that callbacks will always execute
when a livepatch is enabled/disabled.  For patch target kernel modules,
callbacks will only execute if the target module is loaded.  When a
module target is (un)loaded, its callbacks will execute only if the
livepatch module is enabled.

The pre-patch callback, if specified, is expected to return a status
code (0 for success, -ERRNO on error).  An error status code indicates
to the livepatching core that patching of the current klp_object is not
safe and to stop the current patching request.  (When no pre-patch
callback is provided, the transition is assumed to be safe.)  If a
pre-patch callback returns failure, the kernel's module loader will:

  - Refuse to load a livepatch, if the livepatch is loaded after
    targeted code.

    or:

  - Refuse to load a module, if the livepatch was already successfully
    loaded.

No post-patch, pre-unpatch, or post-unpatch callbacks will be executed
for a given klp_object if the object failed to patch, due to a failed
pre_patch callback or for any other reason.

If a patch transition is reversed, no pre-unpatch handlers will be run
(this follows the previously mentioned symmetry -- pre-unpatch callbacks
will only occur if their corresponding post-patch callback executed).

If the object did successfully patch, but the patch transition never
started for some reason (e.g., if another object failed to patch),
only the post-unpatch callback will be called.

4. Use cases
============

Sample livepatch modules demonstrating the callback API can be found in
samples/livepatch/ directory.  These samples were modified for use in
kselftests and can be found in the lib/livepatch directory.

Global data update
------------------

A pre-patch callback can be useful to update a global variable.  For
example, 75ff39ccc1bd ("tcp: make challenge acks less predictable")
changes a global sysctl, as well as patches the tcp_send_challenge_ack()
function.

In this case, if we're being super paranoid, it might make sense to
patch the data *after* patching is complete with a post-patch callback,
so that tcp_send_challenge_ack() could first be changed to read
sysctl_tcp_challenge_ack_limit with READ_ONCE.

__init and probe function patches support
-----------------------------------------

Although __init and probe functions are not directly livepatch-able, it
may be possible to implement similar updates via pre/post-patch
callbacks.

The commit ``48900cb6af42 ("virtio-net: drop NETIF_F_FRAGLIST")`` change the way that
virtnet_probe() initialized its driver's net_device features.  A
pre/post-patch callback could iterate over all such devices, making a
similar change to their hw_features value.  (Client functions of the
value may need to be updated accordingly.)