# Clocks, signals and platform services

---

# The Common Clk Framework

_Peios Kernel / Hardware and drivers / Driver development / Clocks, signals and platform services_

> This document endeavours to explain the common clk framework details, and how to port a platform over to this framework. It is not yet a detailed explanation of the clock api in include/linux/clk.h, but perhaps someday it will include that…

<a id="rst-the-common-clk-framework"></a>

**Author:** Mike Turquette &lt;[mturquette@ti.com](<mailto:mturquette@ti.com>)&gt;

This document endeavours to explain the common clk framework details, and how to port a platform over to this framework.  It is not yet a detailed explanation of the clock api in include/linux/clk.h, but perhaps someday it will include that information.

<a id="rst-introduction-and-interface-split"></a>

## Introduction and interface split

The common clk framework is an interface to control the clock nodes available on various devices today.  This may come in the form of clock gating, rate adjustment, muxing or other operations.  This framework is enabled with the CONFIG_COMMON_CLK option.

The interface itself is divided into two halves, each shielded from the details of its counterpart.  First is the common definition of struct clk which unifies the framework-level accounting and infrastructure that has traditionally been duplicated across a variety of platforms.  Second is a common implementation of the clk.h api, defined in drivers/clk/clk.c.  Finally there is struct clk_ops, whose operations are invoked by the clk api implementation.

The second half of the interface is comprised of the hardware-specific callbacks registered with struct clk_ops and the corresponding hardware-specific structures needed to model a particular clock.  For the remainder of this document any reference to a callback in struct clk_ops, such as .enable or .set_rate, implies the hardware-specific implementation of that code.  Likewise, references to struct clk_foo serve as a convenient shorthand for the implementation of the hardware-specific bits for the hypothetical "foo" hardware.

Tying the two halves of this interface together is struct clk_hw, which is defined in struct clk_foo and pointed to within struct clk_core.  This allows for easy navigation between the two discrete halves of the common clock interface.

<a id="rst-common-data-structures-and-api"></a>

## Common data structures and api

Below is the common struct clk_core definition from drivers/clk/clk.c, modified for brevity:



```text
struct clk_core {
        const char              *name;
        const struct clk_ops    *ops;
        struct clk_hw           *hw;
        struct module           *owner;
        struct clk_core         *parent;
        const char              **parent_names;
        struct clk_core         **parents;
        u8                      num_parents;
        u8                      new_parent_index;
        ...
};
```

The members above make up the core of the clk tree topology.  The clk api itself defines several driver-facing functions which operate on struct clk.  That api is documented in include/linux/clk.h.

Platforms and devices utilizing the common struct clk_core use the struct clk_ops pointer in struct clk_core to perform the hardware-specific parts of the operations defined in clk-provider.h:



```text
struct clk_ops {
        int             (*prepare)(struct clk_hw *hw);
        void            (*unprepare)(struct clk_hw *hw);
        int             (*is_prepared)(struct clk_hw *hw);
        void            (*unprepare_unused)(struct clk_hw *hw);
        int             (*enable)(struct clk_hw *hw);
        void            (*disable)(struct clk_hw *hw);
        int             (*is_enabled)(struct clk_hw *hw);
        void            (*disable_unused)(struct clk_hw *hw);
        unsigned long   (*recalc_rate)(struct clk_hw *hw,
                                        unsigned long parent_rate);
        long            (*round_rate)(struct clk_hw *hw,
                                        unsigned long rate,
                                        unsigned long *parent_rate);
        int             (*determine_rate)(struct clk_hw *hw,
                                          struct clk_rate_request *req);
        int             (*set_parent)(struct clk_hw *hw, u8 index);
        u8              (*get_parent)(struct clk_hw *hw);
        int             (*set_rate)(struct clk_hw *hw,
                                    unsigned long rate,
                                    unsigned long parent_rate);
        int             (*set_rate_and_parent)(struct clk_hw *hw,
                                    unsigned long rate,
                                    unsigned long parent_rate,
                                    u8 index);
        unsigned long   (*recalc_accuracy)(struct clk_hw *hw,
                                        unsigned long parent_accuracy);
        int             (*get_phase)(struct clk_hw *hw);
        int             (*set_phase)(struct clk_hw *hw, int degrees);
        void            (*init)(struct clk_hw *hw);
        void            (*debug_init)(struct clk_hw *hw,
                                      struct dentry *dentry);
};
```

<a id="rst-hardware-clk-implementations"></a>

## Hardware clk implementations

The strength of the common struct clk_core comes from its .ops and .hw pointers which abstract the details of struct clk from the hardware-specific bits, and vice versa.  To illustrate consider the simple gateable clk implementation in drivers/clk/clk-gate.c:



```text
struct clk_gate {
        struct clk_hw   hw;
        void __iomem    *reg;
        u8              bit_idx;
        ...
};
```

struct clk_gate contains struct clk_hw hw as well as hardware-specific knowledge about which register and bit controls this clk's gating. Nothing about clock topology or accounting, such as enable_count or notifier_count, is needed here.  That is all handled by the common framework code and struct clk_core.

Let's walk through enabling this clk from driver code:



```text
struct clk *clk;
clk = clk_get(NULL, "my_gateable_clk");

clk_prepare(clk);
clk_enable(clk);
```

The call graph for clk_enable is very simple:



```text
clk_enable(clk);
        clk->ops->enable(clk->hw);
        [resolves to...]
                clk_gate_enable(hw);
                [resolves struct clk gate with to_clk_gate(hw)]
                        clk_gate_set_bit(gate);
```

And the definition of clk_gate_set_bit:



```text
static void clk_gate_set_bit(struct clk_gate *gate)
{
        u32 reg;

        reg = __raw_readl(gate->reg);
        reg |= BIT(gate->bit_idx);
        writel(reg, gate->reg);
}
```

Note that to_clk_gate is defined as:



```text
#define to_clk_gate(_hw) container_of(_hw, struct clk_gate, hw)
```

This pattern of abstraction is used for every clock hardware representation.

<a id="rst-supporting-your-own-clk-hardware"></a>

## Supporting your own clk hardware

When implementing support for a new type of clock it is only necessary to include the following header:



```text
#include <linux/clk-provider.h>
```

To construct a clk hardware structure for your platform you must define the following:



```text
struct clk_foo {
        struct clk_hw hw;
        ... hardware specific data goes here ...
};
```

To take advantage of your data you'll need to support valid operations for your clk:



```text
struct clk_ops clk_foo_ops = {
        .enable         = &clk_foo_enable,
        .disable        = &clk_foo_disable,
};
```

Implement the above functions using container_of:



```text
#define to_clk_foo(_hw) container_of(_hw, struct clk_foo, hw)

int clk_foo_enable(struct clk_hw *hw)
{
        struct clk_foo *foo;

        foo = to_clk_foo(hw);

        ... perform magic on foo ...

        return 0;
};
```

Below is a matrix detailing which clk_ops are mandatory based upon the hardware capabilities of that clock.  A cell marked as "y" means mandatory, a cell marked as "n" implies that either including that callback is invalid or otherwise unnecessary.  Empty cells are either optional or must be evaluated on a case-by-case basis.


<table>
<caption>clock hardware characteristics</caption>
<thead>
<tr>
<th>




</th>
<th>


gate

</th>
<th>


change rate

</th>
<th>


single parent

</th>
<th>


multiplexer

</th>
<th>


root

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


.prepare

</td>
<td>




</td>
<td>




</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


.unprepare

</td>
<td>




</td>
<td>




</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>




</td>
<td>




</td>
<td>




</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


.enable

</td>
<td>


y

</td>
<td>




</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


.disable

</td>
<td>


y

</td>
<td>




</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


.is_enabled

</td>
<td>


y

</td>
<td>




</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>




</td>
<td>




</td>
<td>




</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


.recalc_rate

</td>
<td>




</td>
<td>


y

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


.round_rate

</td>
<td>




</td>
<td>


y <a id="rst-footnote-reference-1"></a>[1](#rst-footnote-1)

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


.determine_rate

</td>
<td>




</td>
<td>


y <a id="rst-footnote-reference-2"></a>[1](#rst-footnote-1)

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


.set_rate

</td>
<td>




</td>
<td>


y

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>




</td>
<td>




</td>
<td>




</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


.set_parent

</td>
<td>




</td>
<td>




</td>
<td>


n

</td>
<td>


y

</td>
<td>


n

</td>
</tr>
<tr>
<td>


.get_parent

</td>
<td>




</td>
<td>




</td>
<td>


n

</td>
<td>


y

</td>
<td>


n

</td>
</tr>
<tr>
<td>




</td>
<td>




</td>
<td>




</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


.recalc_accuracy

</td>
<td>




</td>
<td>




</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>




</td>
<td>




</td>
<td>




</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


.init

</td>
<td>




</td>
<td>




</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
</tbody>
</table>

<a id="rst-footnote-1"></a>



**[1]** either one of round_rate or determine_rate is required.

Finally, register your clock at run-time with a hardware-specific registration function.  This function simply populates struct clk_foo's data and then passes the common struct clk parameters to the framework with a call to:



```text
clk_register(...)
```

See the basic clock types in `drivers/clk/clk-*.c` for examples.

<a id="rst-disabling-clock-gating-of-unused-clocks"></a>

## Disabling clock gating of unused clocks

Sometimes during development it can be useful to be able to bypass the default disabling of unused clocks. For example, if drivers aren't enabling clocks properly but rely on them being on from the bootloader, bypassing the disabling means that the driver will remain functional while the issues are sorted out.

You can see which clocks have been disabled by booting your kernel with these parameters:



```text
tp_printk trace_event=clk:clk_disable
```

To bypass this disabling, include "clk_ignore_unused" in the bootargs to the kernel.

<a id="rst-locking"></a>

## Locking

The common clock framework uses two global locks, the prepare lock and the enable lock.

The enable lock is a spinlock and is held across calls to the .enable, .disable operations. Those operations are thus not allowed to sleep, and calls to the clk_enable(), clk_disable() API functions are allowed in atomic context.

For clk_is_enabled() API, it is also designed to be allowed to be used in atomic context. However, it doesn't really make any sense to hold the enable lock in core, unless you want to do something else with the information of the enable state with that lock held. Otherwise, seeing if a clk is enabled is a one-shot read of the enabled state, which could just as easily change after the function returns because the lock is released. Thus the user of this API needs to handle synchronizing the read of the state with whatever they're using it for to make sure that the enable state doesn't change during that time.

The prepare lock is a mutex and is held across calls to all other operations. All those operations are allowed to sleep, and calls to the corresponding API functions are not allowed in atomic context.

This effectively divides operations in two groups from a locking perspective.

Drivers don't need to manually protect resources shared between the operations of one group, regardless of whether those resources are shared by multiple clocks or not. However, access to resources that are shared between operations of the two groups needs to be protected by the drivers. An example of such a resource would be a register that controls both the clock rate and the clock enable/disable state.

The clock framework is reentrant, in that a driver is allowed to call clock framework functions from within its implementation of clock operations. This can for instance cause a .set_rate operation of one clock being called from within the .set_rate operation of another clock. This case must be considered in the driver implementations, but the code flow is usually controlled by the driver in that case.

Note that locking must also be considered when code outside of the common clock framework needs to access resources used by the clock operations. This is considered out of scope of this document.

---

# Device Frequency Scaling

_Peios Kernel / Hardware and drivers / Driver development / Clocks, signals and platform services_

> This framework provides a standard kernel interface for Dynamic Voltage and Frequency Switching on arbitrary devices.

<a id="rst-device-frequency-scaling"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-introduction"></a>

## Introduction

This framework provides a standard kernel interface for Dynamic Voltage and Frequency Switching on arbitrary devices.

It exposes controls for adjusting frequency through sysfs files which are similar to the cpufreq subsystem.

Devices for which current usage can be measured can have their frequency automatically adjusted by governors.

<a id="rst-api"></a>

## API

Device drivers need to initialize a `devfreq_profile` and call the `devfreq_add_device()` function to create a `devfreq` instance.


#### <a id="c-struct-devfreq_dev_status"></a>`struct devfreq_dev_status`

Data given from devfreq user device to governors. Represents the performance statistics.

**Definition**

```c
struct devfreq_dev_status {
    unsigned long total_time;
    unsigned long busy_time;
    unsigned long current_frequency;
    void *private_data;
};
```

**Members**

- `total_time`: The total time represented by this instance of
  devfreq_dev_status
- `busy_time`: The time that the device was working among the
  total_time.
- `current_frequency`: The operating frequency.
- `private_data`: An entry not specified by the devfreq framework.
  A device and a specific governor may have their
  own protocol with private_data. However, because
  this is governor-specific, a governor using this
  will be only compatible with devices aware of it.

#### <a id="c-struct-devfreq_dev_profile"></a>`struct devfreq_dev_profile`

Devfreq's user device profile

**Definition**

```c
struct devfreq_dev_profile {
    unsigned long initial_freq;
    unsigned int polling_ms;
    enum devfreq_timer timer;
    int (*target)(struct device *dev, unsigned long *freq, u32 flags);
    int (*get_dev_status)(struct device *dev, struct devfreq_dev_status *stat);
    int (*get_cur_freq)(struct device *dev, unsigned long *freq);
    void (*exit)(struct device *dev);
    unsigned long *freq_table;
    unsigned int max_state;
    bool is_cooling_device;
    const struct attribute_group **dev_groups;
};
```

**Members**

- `initial_freq`: The operating frequency when [`devfreq_add_device()`](#c-devfreq_add_device) is
  called.
- `polling_ms`: The polling interval in ms. 0 disables polling.
- `timer`: Timer type is either deferrable or delayed timer.
- `target`: The device should set its operating frequency at
  freq or lowest-upper-than-freq value. If freq is
  higher than any operable frequency, set maximum.
  Before returning, target function should set
  freq at the current frequency.
  The "flags" parameter's possible values are
  explained above with "DEVFREQ_FLAG_*" macros.
- `get_dev_status`: The device should provide the current performance
  status to devfreq. Governors are recommended not to
  use this directly. Instead, governors are recommended
  to use `devfreq_update_stats()` along with
  devfreq.last_status.
- `get_cur_freq`: The device should provide the current frequency
  at which it is operating.
- `exit`: An optional callback that is called when devfreq
  is removing the devfreq object due to error or
  from [`devfreq_remove_device()`](#c-devfreq_remove_device) call. If the user
  has registered devfreq->nb at a notifier-head,
  this is the time to unregister it.
- `freq_table`: Optional list of frequencies to support statistics
  and freq_table must be generated in ascending order.
- `max_state`: The size of freq_table.
- `is_cooling_device`: A self-explanatory boolean giving the device a
  cooling effect property.
- `dev_groups`: Optional device-specific sysfs attribute groups that to
  be attached to the devfreq device.

#### <a id="c-struct-devfreq_stats"></a>`struct devfreq_stats`

Statistics of devfreq device behavior

**Definition**

```c
struct devfreq_stats {
    unsigned int total_trans;
    unsigned int *trans_table;
    u64 *time_in_state;
    u64 last_update;
};
```

**Members**

- `total_trans`: Number of devfreq transitions.
- `trans_table`: Statistics of devfreq transitions.
- `time_in_state`: Statistics of devfreq states.
- `last_update`: The last time stats were updated.

#### <a id="c-struct-devfreq"></a>`struct devfreq`

Device devfreq structure

**Definition**

```c
struct devfreq {
    struct list_head node;
    struct mutex lock;
    struct device dev;
    struct devfreq_dev_profile *profile;
    const struct devfreq_governor *governor;
    struct opp_table *opp_table;
    struct notifier_block nb;
    struct delayed_work work;
    unsigned long *freq_table;
    unsigned int max_state;
    unsigned long previous_freq;
    struct devfreq_dev_status last_status;
    void *data;
    void *governor_data;
    struct dev_pm_qos_request user_min_freq_req;
    struct dev_pm_qos_request user_max_freq_req;
    unsigned long scaling_min_freq;
    unsigned long scaling_max_freq;
    bool stop_polling;
    unsigned long suspend_freq;
    unsigned long resume_freq;
    atomic_t suspend_count;
    struct devfreq_stats stats;
    struct srcu_notifier_head transition_notifier_list;
    struct thermal_cooling_device *cdev;
    struct notifier_block nb_min;
    struct notifier_block nb_max;
};
```

**Members**

- `node`: list node - contains the devices with devfreq that have been
  registered.
- `lock`: a mutex to protect accessing devfreq.
- `dev`: device registered by devfreq class. dev.parent is the device
  using devfreq.
- `profile`: device-specific devfreq profile
- `governor`: method how to choose frequency based on the usage.
- `opp_table`: Reference to OPP table of dev.parent, if one exists.
- `nb`: notifier block used to notify devfreq object that it should
  reevaluate operable frequencies. Devfreq users may use
  devfreq.nb to the corresponding register notifier call chain.
- `work`: delayed work for load monitoring.
- `freq_table`: current frequency table used by the devfreq driver.
- `max_state`: count of entry present in the frequency table.
- `previous_freq`: previously configured frequency value.
- `last_status`: devfreq user device info, performance statistics
- `data`: devfreq driver pass to governors, governor should not change it.
- `governor_data`: private data for governors, devfreq core doesn't touch it.
- `user_min_freq_req`: PM QoS minimum frequency request from user (via sysfs)
- `user_max_freq_req`: PM QoS maximum frequency request from user (via sysfs)
- `scaling_min_freq`: Limit minimum frequency requested by OPP interface
- `scaling_max_freq`: Limit maximum frequency requested by OPP interface
- `stop_polling`: devfreq polling status of a device.
- `suspend_freq`: frequency of a device set during suspend phase.
- `resume_freq`: frequency of a device set in resume phase.
- `suspend_count`: suspend requests counter for a device.
- `stats`: Statistics of devfreq device behavior
- `transition_notifier_list`: list head of DEVFREQ_TRANSITION_NOTIFIER notifier
- `cdev`: Cooling device pointer if the devfreq has cooling property
- `nb_min`: Notifier block for DEV_PM_QOS_MIN_FREQUENCY
- `nb_max`: Notifier block for DEV_PM_QOS_MAX_FREQUENCY

**Description**

This structure stores the devfreq information for a given device.

Note that when a governor accesses entries in struct devfreq in its
functions except for the context of callbacks defined in struct
devfreq_governor, the governor should protect its access with the
struct mutex lock in struct devfreq. A governor may use this mutex
to protect its own private data in `void *data` as well.

#### <a id="c-struct-devfreq_simple_ondemand_data"></a>`struct devfreq_simple_ondemand_data`

`void *data` fed to struct devfreq and devfreq_add_device

**Definition**

```c
struct devfreq_simple_ondemand_data {
    unsigned int upthreshold;
    unsigned int downdifferential;
};
```

**Members**

- `upthreshold`: If the load is over this value, the frequency jumps.
  Specify 0 to use the default. Valid value = 0 to 100.
- `downdifferential`: If the load is under upthreshold - downdifferential,
  the governor may consider slowing the frequency down.
  Specify 0 to use the default. Valid value = 0 to 100.
  downdifferential \< upthreshold must hold.

**Description**

If the fed devfreq_simple_ondemand_data pointer is NULL to the governor,
the governor uses the default values.

#### <a id="c-struct-devfreq_passive_data"></a>`struct devfreq_passive_data`

`void *data` fed to struct devfreq and devfreq_add_device

**Definition**

```c
struct devfreq_passive_data {
    struct devfreq *parent;
    int (*get_target_freq)(struct devfreq *this, unsigned long *freq);
    enum devfreq_parent_dev_type parent_type;
    struct devfreq *this;
    struct notifier_block nb;
    struct list_head cpu_data_list;
};
```

**Members**

- `parent`: the devfreq instance of parent device.
- `get_target_freq`: Optional callback, Returns desired operating frequency
  for the device using passive governor. That is called
  when passive governor should decide the next frequency
  by using the new frequency of parent devfreq device
  using governors except for passive governor.
  If the devfreq device has the specific method to decide
  the next frequency, should use this callback.
- `parent_type`: the parent type of the device.
- `this`: the devfreq instance of own device.
- `nb`: the notifier block for DEVFREQ_TRANSITION_NOTIFIER or
  CPUFREQ_TRANSITION_NOTIFIER list.
- `cpu_data_list`: the list of cpu frequency data for all cpufreq_policy.

**Description**

The devfreq_passive_data have to set the devfreq instance of parent
device with governors except for the passive governor. But, don't need to
initialize the 'this' and 'nb' field because the devfreq core will handle
them.



#### <a id="c-struct-devfreq_event_dev"></a>`struct devfreq_event_dev`

the devfreq-event device

**Definition**

```c
struct devfreq_event_dev {
    struct list_head node;
    struct device dev;
    struct mutex lock;
    u32 enable_count;
    const struct devfreq_event_desc *desc;
};
```

**Members**

- `node`: Contain the devfreq-event device that have been registered.
- `dev`: the device registered by devfreq-event class. dev.parent is
  the device using devfreq-event.
- `lock`: a mutex to protect accessing devfreq-event.
- `enable_count`: the number of enable function have been called.
- `desc`: the description for devfreq-event device.

**Description**

This structure contains devfreq-event device information.

#### <a id="c-struct-devfreq_event_data"></a>`struct devfreq_event_data`

the devfreq-event data

**Definition**

```c
struct devfreq_event_data {
    unsigned long load_count;
    unsigned long total_count;
};
```

**Members**

- `load_count`: load count of devfreq-event device for the given period.
- `total_count`: total count of devfreq-event device for the given period.
  each count may represent a clock cycle, a time unit
  (ns/us/...), or anything the device driver wants.
  Generally, utilization is load_count / total_count.

**Description**

This structure contains the data of devfreq-event device for polling period.

#### <a id="c-struct-devfreq_event_ops"></a>`struct devfreq_event_ops`

the operations of devfreq-event device

**Definition**

```c
struct devfreq_event_ops {
    int (*enable)(struct devfreq_event_dev *edev);
    int (*disable)(struct devfreq_event_dev *edev);
    int (*reset)(struct devfreq_event_dev *edev);
    int (*set_event)(struct devfreq_event_dev *edev);
    int (*get_event)(struct devfreq_event_dev *edev, struct devfreq_event_data *edata);
};
```

**Members**

- `enable`: Enable the devfreq-event device.
- `disable`: Disable the devfreq-event device.
- `reset`: Reset all setting of the devfreq-event device.
- `set_event`: Set the specific event type for the devfreq-event device.
- `get_event`: Get the result of the devfreq-event devie with specific
  event type.

**Description**

This structure contains devfreq-event device operations which can be
implemented by devfreq-event device drivers.

#### <a id="c-struct-devfreq_event_desc"></a>`struct devfreq_event_desc`

the descriptor of devfreq-event device

**Definition**

```c
struct devfreq_event_desc {
    const char *name;
    u32 event_type;
    void *driver_data;
    const struct devfreq_event_ops *ops;
};
```

**Members**

- `name`: the name of devfreq-event device.
- `event_type`: the type of the event determined and used by driver
- `driver_data`: the private data for devfreq-event driver.
- `ops`: the operation to control devfreq-event device.

**Description**

Each devfreq-event device is described with a this structure.
This structure contains the various data for devfreq-event device.
The event_type describes what is going to be counted in the register.
It might choose to count e.g. read requests, write data in bytes, etc.
The full supported list of types is present in specyfic header in:
include/dt-bindings/pmu/.



#### <a id="c-devfreq_get_freq_range"></a>`devfreq_get_freq_range()`

```c
void devfreq_get_freq_range(struct devfreq *devfreq, unsigned long *min_freq, unsigned long *max_freq)
```

Get the current freq range

**Parameters**

- `struct devfreq *devfreq`: the devfreq instance
- `unsigned long *min_freq`: the min frequency
- `unsigned long *max_freq`: the max frequency

**Description**

This takes into consideration all constraints.

#### <a id="c-devfreq_update_status"></a>`devfreq_update_status()`

```c
int devfreq_update_status(struct devfreq *devfreq, unsigned long freq)
```

Update statistics of devfreq behavior

**Parameters**

- `struct devfreq *devfreq`: the devfreq instance
- `unsigned long freq`: the update target frequency

#### <a id="c-devfreq_update_target"></a>`devfreq_update_target()`

```c
int devfreq_update_target(struct devfreq *devfreq, unsigned long freq)
```

Reevaluate the device and configure frequency on the final stage.

**Parameters**

- `struct devfreq *devfreq`: the devfreq instance.
- `unsigned long freq`: the new frequency of parent device. This argument
  is only used for devfreq device using passive governor.

**Note**

- Lock devfreq->lock before calling devfreq_update_target. This function

  should be only used by both [`update_devfreq()`](#c-update_devfreq) and devfreq governors.

#### <a id="c-update_devfreq"></a>`update_devfreq()`

```c
int update_devfreq(struct devfreq *devfreq)
```

Reevaluate the device and configure frequency.

**Parameters**

- `struct devfreq *devfreq`: the devfreq instance.

**Note**

- Lock devfreq->lock before calling update_devfreq

  This function is exported for governors.

#### <a id="c-devfreq_monitor_start"></a>`devfreq_monitor_start()`

```c
void devfreq_monitor_start(struct devfreq *devfreq)
```

Start load monitoring of devfreq instance

**Parameters**

- `struct devfreq *devfreq`: the devfreq instance.

**Description**

Helper function for starting devfreq device load monitoring. By default,
deferrable timer is used for load monitoring. But the users can change this
behavior using the "timer" type in devfreq_dev_profile. This function will be
called by devfreq governor in response to the DEVFREQ_GOV_START event
generated while adding a device to the devfreq framework.

#### <a id="c-devfreq_monitor_stop"></a>`devfreq_monitor_stop()`

```c
void devfreq_monitor_stop(struct devfreq *devfreq)
```

Stop load monitoring of a devfreq instance

**Parameters**

- `struct devfreq *devfreq`: the devfreq instance.

**Description**

Helper function to stop devfreq device load monitoring. Function
to be called from governor in response to DEVFREQ_GOV_STOP
event when device is removed from devfreq framework.

#### <a id="c-devfreq_monitor_suspend"></a>`devfreq_monitor_suspend()`

```c
void devfreq_monitor_suspend(struct devfreq *devfreq)
```

Suspend load monitoring of a devfreq instance

**Parameters**

- `struct devfreq *devfreq`: the devfreq instance.

**Description**

Helper function to suspend devfreq device load monitoring. Function
to be called from governor in response to DEVFREQ_GOV_SUSPEND
event or when polling interval is set to zero.

**Note**

Though this function is same as [`devfreq_monitor_stop()`](#c-devfreq_monitor_stop),
intentionally kept separate to provide hooks for collecting
transition statistics.

#### <a id="c-devfreq_monitor_resume"></a>`devfreq_monitor_resume()`

```c
void devfreq_monitor_resume(struct devfreq *devfreq)
```

Resume load monitoring of a devfreq instance

**Parameters**

- `struct devfreq *devfreq`: the devfreq instance.

**Description**

Helper function to resume devfreq device load monitoring. Function
to be called from governor in response to DEVFREQ_GOV_RESUME
event or when polling interval is set to non-zero.

#### <a id="c-devfreq_update_interval"></a>`devfreq_update_interval()`

```c
void devfreq_update_interval(struct devfreq *devfreq, unsigned int *delay)
```

Update device devfreq monitoring interval

**Parameters**

- `struct devfreq *devfreq`: the devfreq instance.
- `unsigned int *delay`: new polling interval to be set.

**Description**

Helper function to set new load monitoring polling interval. Function
to be called from governor in response to DEVFREQ_GOV_UPDATE_INTERVAL event.

#### <a id="c-devfreq_add_device"></a>`devfreq_add_device()`

```c
struct devfreq * devfreq_add_device(struct device *dev, struct devfreq_dev_profile *profile, const char *governor_name, void *data)
```

Add devfreq feature to the device

**Parameters**

- `struct device *dev`: the device to add devfreq feature.
- `struct devfreq_dev_profile *profile`: device-specific profile to run devfreq.
- `const char *governor_name`: name of the policy to choose frequency.
- `void *data`: devfreq driver pass to governors, governor should not change it.

#### <a id="c-devfreq_remove_device"></a>`devfreq_remove_device()`

```c
int devfreq_remove_device(struct devfreq *devfreq)
```

Remove devfreq feature from a device.

**Parameters**

- `struct devfreq *devfreq`: the devfreq instance to be removed

**Description**

The opposite of [`devfreq_add_device()`](#c-devfreq_add_device).

#### <a id="c-devm_devfreq_add_device"></a>`devm_devfreq_add_device()`

```c
struct devfreq * devm_devfreq_add_device(struct device *dev, struct devfreq_dev_profile *profile, const char *governor_name, void *data)
```

Resource-managed [`devfreq_add_device()`](#c-devfreq_add_device)

**Parameters**

- `struct device *dev`: the device to add devfreq feature.
- `struct devfreq_dev_profile *profile`: device-specific profile to run devfreq.
- `const char *governor_name`: name of the policy to choose frequency.
- `void *data`: devfreq driver pass to governors, governor should not change it.

**Description**

This function manages automatically the memory of devfreq device using device
resource management and simplify the free operation for memory of devfreq
device.

#### <a id="c-devm_devfreq_remove_device"></a>`devm_devfreq_remove_device()`

```c
void devm_devfreq_remove_device(struct device *dev, struct devfreq *devfreq)
```

Resource-managed [`devfreq_remove_device()`](#c-devfreq_remove_device)

**Parameters**

- `struct device *dev`: the device from which to remove devfreq feature.
- `struct devfreq *devfreq`: the devfreq instance to be removed

#### <a id="c-devfreq_suspend_device"></a>`devfreq_suspend_device()`

```c
int devfreq_suspend_device(struct devfreq *devfreq)
```

Suspend devfreq of a device.

**Parameters**

- `struct devfreq *devfreq`: the devfreq instance to be suspended

**Description**

This function is intended to be called by the pm callbacks
(e.g., runtime_suspend, suspend) of the device driver that
holds the devfreq.

#### <a id="c-devfreq_resume_device"></a>`devfreq_resume_device()`

```c
int devfreq_resume_device(struct devfreq *devfreq)
```

Resume devfreq of a device.

**Parameters**

- `struct devfreq *devfreq`: the devfreq instance to be resumed

**Description**

This function is intended to be called by the pm callbacks
(e.g., runtime_resume, resume) of the device driver that
holds the devfreq.

#### <a id="c-devfreq_add_governor"></a>`devfreq_add_governor()`

```c
int devfreq_add_governor(struct devfreq_governor *governor)
```

Add devfreq governor

**Parameters**

- `struct devfreq_governor *governor`: the devfreq governor to be added

#### <a id="c-devm_devfreq_add_governor"></a>`devm_devfreq_add_governor()`

```c
int devm_devfreq_add_governor(struct device *dev, struct devfreq_governor *governor)
```

Add devfreq governor

**Parameters**

- `struct device *dev`: device which adds devfreq governor
- `struct devfreq_governor *governor`: the devfreq governor to be added

**Description**

This is a resource-managed variant of [`devfreq_add_governor()`](#c-devfreq_add_governor).

#### <a id="c-devfreq_remove_governor"></a>`devfreq_remove_governor()`

```c
int devfreq_remove_governor(struct devfreq_governor *governor)
```

Remove devfreq feature from a device.

**Parameters**

- `struct devfreq_governor *governor`: the devfreq governor to be removed

#### <a id="c-devfreq_recommended_opp"></a>`devfreq_recommended_opp()`

```c
struct dev_pm_opp * devfreq_recommended_opp(struct device *dev, unsigned long *freq, u32 flags)
```

Helper function to get proper OPP for the freq value given to target callback.

**Parameters**

- `struct device *dev`: The devfreq user device. (parent of devfreq)
- `unsigned long *freq`: The frequency given to target function
- `u32 flags`: Flags handed from devfreq framework.

**Description**

The callers are required to call `dev_pm_opp_put()` for the returned OPP after
use.

#### <a id="c-devfreq_register_opp_notifier"></a>`devfreq_register_opp_notifier()`

```c
int devfreq_register_opp_notifier(struct device *dev, struct devfreq *devfreq)
```

Helper function to get devfreq notified for any changes in the OPP availability changes

**Parameters**

- `struct device *dev`: The devfreq user device. (parent of devfreq)
- `struct devfreq *devfreq`: The devfreq object.

#### <a id="c-devfreq_unregister_opp_notifier"></a>`devfreq_unregister_opp_notifier()`

```c
int devfreq_unregister_opp_notifier(struct device *dev, struct devfreq *devfreq)
```

Helper function to stop getting devfreq notified for any changes in the OPP availability changes anymore.

**Parameters**

- `struct device *dev`: The devfreq user device. (parent of devfreq)
- `struct devfreq *devfreq`: The devfreq object.

**Description**

At `exit()` callback of devfreq_dev_profile, this must be included if
devfreq_recommended_opp is used.

#### <a id="c-devm_devfreq_register_opp_notifier"></a>`devm_devfreq_register_opp_notifier()`

```c
int devm_devfreq_register_opp_notifier(struct device *dev, struct devfreq *devfreq)
```

Resource-managed [`devfreq_register_opp_notifier()`](#c-devfreq_register_opp_notifier)

**Parameters**

- `struct device *dev`: The devfreq user device. (parent of devfreq)
- `struct devfreq *devfreq`: The devfreq object.

#### <a id="c-devm_devfreq_unregister_opp_notifier"></a>`devm_devfreq_unregister_opp_notifier()`

```c
void devm_devfreq_unregister_opp_notifier(struct device *dev, struct devfreq *devfreq)
```

Resource-managed [`devfreq_unregister_opp_notifier()`](#c-devfreq_unregister_opp_notifier)

**Parameters**

- `struct device *dev`: The devfreq user device. (parent of devfreq)
- `struct devfreq *devfreq`: The devfreq object.

#### <a id="c-devfreq_register_notifier"></a>`devfreq_register_notifier()`

```c
int devfreq_register_notifier(struct devfreq *devfreq, struct notifier_block *nb, unsigned int list)
```

Register a driver with devfreq

**Parameters**

- `struct devfreq *devfreq`: The devfreq object.
- `struct notifier_block *nb`: The notifier block to register.
- `unsigned int list`: DEVFREQ_TRANSITION_NOTIFIER.

#### <a id="c-devm_devfreq_register_notifier"></a>`devm_devfreq_register_notifier()`

```c
int devm_devfreq_register_notifier(struct device *dev, struct devfreq *devfreq, struct notifier_block *nb, unsigned int list)
```

**Parameters**

- `struct device *dev`: The devfreq user device. (parent of devfreq)
- `struct devfreq *devfreq`: The devfreq object.
- `struct notifier_block *nb`: The notifier block to be unregistered.
- `unsigned int list`: DEVFREQ_TRANSITION_NOTIFIER.

**Description**

- Resource-managed [`devfreq_register_notifier()`](#c-devfreq_register_notifier)

#### <a id="c-devm_devfreq_unregister_notifier"></a>`devm_devfreq_unregister_notifier()`

```c
void devm_devfreq_unregister_notifier(struct device *dev, struct devfreq *devfreq, struct notifier_block *nb, unsigned int list)
```

**Parameters**

- `struct device *dev`: The devfreq user device. (parent of devfreq)
- `struct devfreq *devfreq`: The devfreq object.
- `struct notifier_block *nb`: The notifier block to be unregistered.
- `unsigned int list`: DEVFREQ_TRANSITION_NOTIFIER.

**Description**

- Resource-managed `devfreq_unregister_notifier()`



#### <a id="c-devfreq_event_enable_edev"></a>`devfreq_event_enable_edev()`

```c
int devfreq_event_enable_edev(struct devfreq_event_dev *edev)
```

Enable the devfreq-event dev and increase the enable_count of devfreq-event dev.

**Parameters**

- `struct devfreq_event_dev *edev`: the devfreq-event device

**Description**

Note that this function increase the enable_count and enable the
devfreq-event device. The devfreq-event device should be enabled before
using it by devfreq device.

#### <a id="c-devfreq_event_disable_edev"></a>`devfreq_event_disable_edev()`

```c
int devfreq_event_disable_edev(struct devfreq_event_dev *edev)
```

Disable the devfreq-event dev and decrease the enable_count of the devfreq-event dev.

**Parameters**

- `struct devfreq_event_dev *edev`: the devfreq-event device

**Description**

Note that this function decrease the enable_count and disable the
devfreq-event device. After the devfreq-event device is disabled,
devfreq device can't use the devfreq-event device for get/set/reset
operations.

#### <a id="c-devfreq_event_is_enabled"></a>`devfreq_event_is_enabled()`

```c
bool devfreq_event_is_enabled(struct devfreq_event_dev *edev)
```

Check whether devfreq-event dev is enabled or not.

**Parameters**

- `struct devfreq_event_dev *edev`: the devfreq-event device

**Description**

Note that this function check whether devfreq-event dev is enabled or not.
If return true, the devfreq-event dev is enabeld. If return false, the
devfreq-event dev is disabled.

#### <a id="c-devfreq_event_set_event"></a>`devfreq_event_set_event()`

```c
int devfreq_event_set_event(struct devfreq_event_dev *edev)
```

Set event to devfreq-event dev to start.

**Parameters**

- `struct devfreq_event_dev *edev`: the devfreq-event device

**Description**

Note that this function set the event to the devfreq-event device to start
for getting the event data which could be various event type.

#### <a id="c-devfreq_event_get_event"></a>`devfreq_event_get_event()`

```c
int devfreq_event_get_event(struct devfreq_event_dev *edev, struct devfreq_event_data *edata)
```

Get {load|total}_count from devfreq-event dev.

**Parameters**

- `struct devfreq_event_dev *edev`: the devfreq-event device
- `struct devfreq_event_data *edata`: the calculated data of devfreq-event device

**Description**

Note that this function get the calculated event data from devfreq-event dev
after stoping the progress of whole sequence of devfreq-event dev.

#### <a id="c-devfreq_event_reset_event"></a>`devfreq_event_reset_event()`

```c
int devfreq_event_reset_event(struct devfreq_event_dev *edev)
```

Reset all opeations of devfreq-event dev.

**Parameters**

- `struct devfreq_event_dev *edev`: the devfreq-event device

**Description**

Note that this function stop all operations of devfreq-event dev and reset
the current event data to make the devfreq-event device into initial state.

#### <a id="c-devfreq_event_get_edev_by_phandle"></a>`devfreq_event_get_edev_by_phandle()`

```c
struct devfreq_event_dev * devfreq_event_get_edev_by_phandle(struct device *dev, const char *phandle_name, int index)
```

Get the devfreq-event dev from devicetree.

**Parameters**

- `struct device *dev`: the pointer to the given device
- `const char *phandle_name`: name of property holding a phandle value
- `int index`: the index into list of devfreq-event device

**Description**

Note that this function return the pointer of devfreq-event device.

#### <a id="c-devfreq_event_get_edev_count"></a>`devfreq_event_get_edev_count()`

```c
int devfreq_event_get_edev_count(struct device *dev, const char *phandle_name)
```

Get the count of devfreq-event dev

**Parameters**

- `struct device *dev`: the pointer to the given device
- `const char *phandle_name`: name of property holding a phandle value

**Description**

Note that this function return the count of devfreq-event devices.

#### <a id="c-devfreq_event_add_edev"></a>`devfreq_event_add_edev()`

```c
struct devfreq_event_dev * devfreq_event_add_edev(struct device *dev, struct devfreq_event_desc *desc)
```

Add new devfreq-event device.

**Parameters**

- `struct device *dev`: the device owning the devfreq-event device being created
- `struct devfreq_event_desc *desc`: the devfreq-event device's descriptor which include essential
  data for devfreq-event device.

**Description**

Note that this function add new devfreq-event device to devfreq-event class
list and register the device of the devfreq-event device.

#### <a id="c-devfreq_event_remove_edev"></a>`devfreq_event_remove_edev()`

```c
int devfreq_event_remove_edev(struct devfreq_event_dev *edev)
```

Remove the devfreq-event device registered.

**Parameters**

- `struct devfreq_event_dev *edev`: the devfreq-event device

**Description**

Note that this function removes the registered devfreq-event device.

#### <a id="c-devm_devfreq_event_add_edev"></a>`devm_devfreq_event_add_edev()`

```c
struct devfreq_event_dev * devm_devfreq_event_add_edev(struct device *dev, struct devfreq_event_desc *desc)
```

Resource-managed [`devfreq_event_add_edev()`](#c-devfreq_event_add_edev)

**Parameters**

- `struct device *dev`: the device owning the devfreq-event device being created
- `struct devfreq_event_desc *desc`: the devfreq-event device's descriptor which include essential
  data for devfreq-event device.

**Description**

Note that this function manages automatically the memory of devfreq-event
device using device resource management and simplify the free operation
for memory of devfreq-event device.

#### <a id="c-devm_devfreq_event_remove_edev"></a>`devm_devfreq_event_remove_edev()`

```c
void devm_devfreq_event_remove_edev(struct device *dev, struct devfreq_event_dev *edev)
```

Resource-managed [`devfreq_event_remove_edev()`](#c-devfreq_event_remove_edev)

**Parameters**

- `struct device *dev`: the device owning the devfreq-event device being created
- `struct devfreq_event_dev *edev`: the devfreq-event device

**Description**

Note that this function manages automatically the memory of devfreq-event
device using device resource management.

---

# The Linux kernel dpll subsystem

_Peios Kernel / Hardware and drivers / Driver development / Clocks, signals and platform services_

> PLL - Phase Locked Loop is an electronic circuit which syntonizes clock signal of a device with an external clock signal. Effectively enabling device to run on the same clock signal beat as provided on a PLL input.

<a id="rst-the-linux-kernel-dpll-subsystem"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-dpll"></a>

## DPLL

PLL - Phase Locked Loop is an electronic circuit which syntonizes clock signal of a device with an external clock signal. Effectively enabling device to run on the same clock signal beat as provided on a PLL input.

DPLL - Digital Phase Locked Loop is an integrated circuit which in addition to plain PLL behavior incorporates a digital phase detector and may have digital divider in the loop. As a result, the frequency on DPLL's input and output may be configurable.

<a id="rst-subsystem"></a>

## Subsystem

The main purpose of dpll subsystem is to provide general interface to configure devices that use any kind of Digital PLL and could use different sources of input signal to synchronize to, as well as different types of outputs. The main interface is NETLINK\_GENERIC based protocol with an event monitoring multicast group defined.

<a id="rst-device-object"></a>

## Device object

Single dpll device object means single Digital PLL circuit and bunch of connected pins. It reports the supported modes of operation and current status to the user in response to the `do` request of netlink command `DPLL_CMD_DEVICE_GET` and list of dplls registered in the subsystem with `dump` netlink request of the same command. Changing the configuration of dpll device is done with `do` request of netlink `DPLL_CMD_DEVICE_SET` command. A device handle is `DPLL_A_ID`, it shall be provided to get or set configuration of particular device in the system. It can be obtained with a `DPLL_CMD_DEVICE_GET` `dump` request or a `DPLL_CMD_DEVICE_ID_GET` `do` request, where the one must provide attributes that result in single device match.

<a id="rst-pin-object"></a>

## Pin object

A pin is amorphic object which represents either input or output, it could be internal component of the device, as well as externally connected. The number of pins per dpll vary, but usually multiple pins shall be provided for a single dpll device. Pin's properties, capabilities and status is provided to the user in response to `do` request of netlink `DPLL_CMD_PIN_GET` command. It is also possible to list all the pins that were registered in the system with `dump` request of `DPLL_CMD_PIN_GET` command. Configuration of a pin can be changed by `do` request of netlink `DPLL_CMD_PIN_SET` command. Pin handle is a `DPLL_A_PIN_ID`, it shall be provided to get or set configuration of particular pin in the system. It can be obtained with `DPLL_CMD_PIN_GET` `dump` request or `DPLL_CMD_PIN_ID_GET` `do` request, where user provides attributes that result in single pin match.

<a id="rst-pin-selection"></a>

## Pin selection

In general, selected pin (the one which signal is driving the dpll device) can be obtained from `DPLL_A_PIN_STATE` attribute, and only one pin shall be in `DPLL_PIN_STATE_CONNECTED` state for any dpll device.

Pin selection can be done either manually or automatically, depending on hardware capabilities and active dpll device work mode (`DPLL_A_MODE` attribute). The consequence is that there are differences for each mode in terms of available pin states, as well as for the states the user can request for a dpll device.

In manual mode (`DPLL_MODE_MANUAL`) the user can request or receive one of following pin states:

- `DPLL_PIN_STATE_CONNECTED` - the pin is used to drive dpll device

- `DPLL_PIN_STATE_DISCONNECTED` - the pin is not used to drive dpll device

In automatic mode (`DPLL_MODE_AUTOMATIC`) the user can request or receive one of following pin states:

- `DPLL_PIN_STATE_SELECTABLE` - the pin shall be considered as valid input for automatic selection algorithm

- `DPLL_PIN_STATE_DISCONNECTED` - the pin shall be not considered as a valid input for automatic selection algorithm

In automatic mode (`DPLL_MODE_AUTOMATIC`) the user can only receive pin state `DPLL_PIN_STATE_CONNECTED` once automatic selection algorithm locks a dpll device with one of the inputs.

<a id="rst-shared-pins"></a>

## Shared pins

A single pin object can be attached to multiple dpll devices. Then there are two groups of configuration knobs:

1. Set on a pin - the configuration affects all dpll devices pin is registered to (i.e., `DPLL_A_PIN_FREQUENCY`),

2. Set on a pin-dpll tuple - the configuration affects only selected dpll device (i.e., `DPLL_A_PIN_PRIO`, `DPLL_A_PIN_STATE`, `DPLL_A_PIN_DIRECTION`).

<a id="rst-mux-type-pins"></a>

## MUX-type pins

A pin can be MUX-type, it aggregates child pins and serves as a pin multiplexer. One or more pins are registered with MUX-type instead of being directly registered to a dpll device. Pins registered with a MUX-type pin provide user with additional nested attribute `DPLL_A_PIN_PARENT_PIN` for each parent they were registered with. If a pin was registered with multiple parent pins, they behave like a multiple output multiplexer. In this case output of a `DPLL_CMD_PIN_GET` would contain multiple pin-parent nested attributes with current state related to each parent, like:



```text
'pin': [{{
  'clock-id': 282574471561216,
  'module-name': 'ice',
  'capabilities': 4,
  'id': 13,
  'parent-pin': [
  {'parent-id': 2, 'state': 'connected'},
  {'parent-id': 3, 'state': 'disconnected'}
  ],
  'type': 'synce-eth-port'
  }}]
```

Only one child pin can provide its signal to the parent MUX-type pin at a time, the selection is done by requesting change of a child pin state on desired parent, with the use of `DPLL_A_PIN_PARENT` nested attribute. Example of netlink `set state on parent pin` message format:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_ID`
>
> </td>
> <td>
>
>
>
> child pin id
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_PARENT_PIN`
>
> </td>
> <td>
>
>
>
> nested attribute for requesting configuration related to parent pin
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_PARENT_ID`
>
> </td>
> <td>
>
>
>
> parent pin id
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_STATE`
>
> </td>
> <td>
>
>
>
> requested pin state on parent
>
> </td>
> </tr>
> </tbody>
> </table>

<a id="rst-pin-priority"></a>

## Pin priority

Some devices might offer a capability of automatic pin selection mode (enum value `DPLL_MODE_AUTOMATIC` of `DPLL_A_MODE` attribute). Usually, automatic selection is performed on the hardware level, which means only pins directly connected to the dpll can be used for automatic input pin selection. In automatic selection mode, the user cannot manually select a input pin for the device, instead the user shall provide all directly connected pins with a priority `DPLL_A_PIN_PRIO`, the device would pick a highest priority valid signal and use it to control the DPLL device. Example of netlink `set priority on parent pin` message format:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_ID`
>
> </td>
> <td>
>
>
>
> configured pin id
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_PARENT_DEVICE`
>
> </td>
> <td>
>
>
>
> nested attribute for requesting configuration related to parent dpll device
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_PARENT_ID`
>
> </td>
> <td>
>
>
>
> parent dpll device id
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_PRIO`
>
> </td>
> <td>
>
>
>
> requested pin prio on parent dpll
>
> </td>
> </tr>
> </tbody>
> </table>

Child pin of MUX-type pin is not capable of automatic input pin selection, in order to configure active input of a MUX-type pin, the user needs to request desired pin state of the child pin on the parent pin, as described in the `MUX-type pins` chapter.

<a id="rst-phase-offset-measurement-and-adjustment"></a>

## Phase offset measurement and adjustment

Device may provide ability to measure a phase difference between signals on a pin and its parent dpll device. If pin-dpll phase offset measurement is supported, it shall be provided with `DPLL_A_PIN_PHASE_OFFSET` attribute for each parent dpll device. The reported phase offset may be computed as the average of prior values and the current measurement, using the following formula:

```math
curr\_avg = prev\_avg * \frac{2^N-1}{2^N} + new\_val * \frac{1}{2^N}
```

where `curr_avg` is the current reported phase offset, `prev_avg` is the previously reported value, `new_val` is the current measurement, and `N` is the averaging factor. Configured averaging factor value is provided with `DPLL_A_PHASE_OFFSET_AVG_FACTOR` attribute of a device and value change can be requested with the same attribute with `DPLL_CMD_DEVICE_SET` command.

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
>
> `DPLL_A_PHASE_OFFSET_AVG_FACTOR`
>
> </td>
> <td>
>
>
>
> attr configured value of phase offset averaging factor
>
> </td>
> </tr>
> </tbody>
> </table>

Device may also provide ability to adjust a signal phase on a pin. If pin phase adjustment is supported, minimal and maximal values and granularity that pin handle shall be provided to the user on `DPLL_CMD_PIN_GET` respond with `DPLL_A_PIN_PHASE_ADJUST_MIN`, `DPLL_A_PIN_PHASE_ADJUST_MAX` and `DPLL_A_PIN_PHASE_ADJUST_GRAN` attributes. Configured phase adjust value is provided with `DPLL_A_PIN_PHASE_ADJUST` attribute of a pin, and value change can be requested with the same attribute with `DPLL_CMD_PIN_SET` command.

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_ID`
>
> </td>
> <td>
>
>
>
> configured pin id
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_PHASE_ADJUST_GRAN`
>
> </td>
> <td>
>
>
>
> attr granularity of phase adjustment value
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_PHASE_ADJUST_MIN`
>
> </td>
> <td>
>
>
>
> attr minimum value of phase adjustment
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_PHASE_ADJUST_MAX`
>
> </td>
> <td>
>
>
>
> attr maximum value of phase adjustment
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_PHASE_ADJUST`
>
> </td>
> <td>
>
>
>
> attr configured value of phase adjustment on parent dpll device
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_PARENT_DEVICE`
>
> </td>
> <td>
>
>
>
> nested attribute for requesting configuration on given parent dpll device
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_PARENT_ID`
>
> </td>
> <td>
>
>
>
> parent dpll device id
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_PHASE_OFFSET`
>
> </td>
> <td>
>
>
>
> attr measured phase difference between a pin and parent dpll device
>
> </td>
> </tr>
> </tbody>
> </table>

All phase related values are provided in pico seconds, which represents time difference between signals phase. The negative value means that phase of signal on pin is earlier in time than dpll's signal. Positive value means that phase of signal on pin is later in time than signal of a dpll.

Phase adjust (also min and max) values are integers, but measured phase offset values are fractional with 3-digit decimal places and shell be divided with `DPLL_PIN_PHASE_OFFSET_DIVIDER` to get integer part and modulo divided to get fractional part.

<a id="rst-phase-offset-monitor"></a>

## Phase offset monitor

Phase offset measurement is typically performed against the current active source. However, some DPLL (Digital Phase-Locked Loop) devices may offer the capability to monitor phase offsets across all available inputs. The attribute and current feature state shall be included in the response message of the `DPLL_CMD_DEVICE_GET` command for supported DPLL devices. In such cases, users can also control the feature using the `DPLL_CMD_DEVICE_SET` command by setting the `enum dpll_feature_state` values for the attribute. Once enabled the phase offset measurements for the input shall be returned in the `DPLL_A_PIN_PHASE_OFFSET` attribute.

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
>
> `DPLL_A_PHASE_OFFSET_MONITOR`
>
> </td>
> <td>
>
>
>
> attr state of a feature
>
> </td>
> </tr>
> </tbody>
> </table>

<a id="rst-embedded-sync"></a>

## Embedded SYNC

Device may provide ability to use Embedded SYNC feature. It allows to embed additional SYNC signal into the base frequency of a pin - a one special pulse of base frequency signal every time SYNC signal pulse happens. The user can configure the frequency of Embedded SYNC. The Embedded SYNC capability is always related to a given base frequency and HW capabilities. The user is provided a range of Embedded SYNC frequencies supported, depending on current base frequency configured for the pin.

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_ESYNC_FREQUENCY`
>
> </td>
> <td>
>
>
>
> current Embedded SYNC frequency
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_ESYNC_FREQUENCY_SUPPORTED`
>
> </td>
> <td>
>
>
>
> nest available Embedded SYNC frequency ranges
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_FREQUENCY_MIN`
>
> </td>
> <td>
>
>
>
> attr minimum value of frequency
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_FREQUENCY_MAX`
>
> </td>
> <td>
>
>
>
> attr maximum value of frequency
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_ESYNC_PULSE`
>
> </td>
> <td>
>
>
>
> pulse type of Embedded SYNC
>
> </td>
> </tr>
> </tbody>
> </table>

<a id="rst-reference-sync"></a>

## Reference SYNC

The device may support the Reference SYNC feature, which allows the combination of two inputs into a input pair. In this configuration, clock signals from both inputs are used to synchronize the DPLL device. The higher frequency signal is utilized for the loop bandwidth of the DPLL, while the lower frequency signal is used to syntonize the output signal of the DPLL device. This feature enables the provision of a high-quality loop bandwidth signal from an external source.

A capable input provides a list of inputs that can be bound with to create Reference SYNC. To control this feature, the user must request a desired state for a target pin: use `DPLL_PIN_STATE_CONNECTED` to enable or `DPLL_PIN_STATE_DISCONNECTED` to disable the feature. An input pin can be bound to only one other pin at any given time.

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_REFERENCE_SYNC`
>
> </td>
> <td>
>
>
>
> nested attribute for providing info or requesting configuration of the Reference SYNC feature
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_ID`
>
> </td>
> <td>
>
>
>
> target pin id for Reference SYNC feature
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_STATE`
>
> </td>
> <td>
>
>
>
> state of Reference SYNC connection
>
> </td>
> </tr>
> </tbody>
> </table>

<a id="rst-configuration-commands-group"></a>

## Configuration commands group

Configuration commands are used to get information about registered dpll devices (and pins), as well as set configuration of device or pins. As dpll devices must be abstracted and reflect real hardware, there is no way to add new dpll device via netlink from user space and each device should be registered by its driver.

All netlink commands require `GENL_ADMIN_PERM`. This is to prevent any spamming/DoS from unauthorized userspace applications.

<a id="rst-list-of-netlink-commands-with-possible-attributes"></a>

## List of netlink commands with possible attributes

Constants identifying command types for dpll device uses a `DPLL_CMD_` prefix and suffix according to command purpose. The dpll device related attributes use a `DPLL_A_` prefix and suffix according to attribute purpose.

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
>
> `DPLL_CMD_DEVICE_ID_GET`
>
> </td>
> <td>
>
>
>
> command to get device ID
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_MODULE_NAME`
>
> </td>
> <td>
>
>
>
> attr module name of registerer
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_CLOCK_ID`
>
> </td>
> <td>
>
>
>
> attr Unique Clock Identifier (EUI-64), as defined by the IEEE 1588 standard
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_TYPE`
>
> </td>
> <td>
>
>
>
> attr type of dpll device
>
> </td>
> </tr>
> </tbody>
> </table>
>
>
> <table>
> <tbody>
> <tr>
> <td>
>
>
>
> `DPLL_CMD_DEVICE_GET`
>
> </td>
> <td>
>
>
>
> command to get device info or dump list of available devices
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_ID`
>
> </td>
> <td>
>
>
>
> attr unique dpll device ID
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_MODULE_NAME`
>
> </td>
> <td>
>
>
>
> attr module name of registerer
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_CLOCK_ID`
>
> </td>
> <td>
>
>
>
> attr Unique Clock Identifier (EUI-64), as defined by the IEEE 1588 standard
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_MODE`
>
> </td>
> <td>
>
>
>
> attr selection mode
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_MODE_SUPPORTED`
>
> </td>
> <td>
>
>
>
> attr available selection modes
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_LOCK_STATUS`
>
> </td>
> <td>
>
>
>
> attr dpll device lock status
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_TEMP`
>
> </td>
> <td>
>
>
>
> attr device temperature info
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_TYPE`
>
> </td>
> <td>
>
>
>
> attr type of dpll device
>
> </td>
> </tr>
> </tbody>
> </table>
>
>
> <table>
> <tbody>
> <tr>
> <td>
>
>
>
> `DPLL_CMD_DEVICE_SET`
>
> </td>
> <td>
>
>
>
> command to set dpll device config
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_ID`
>
> </td>
> <td>
>
>
>
> attr internal dpll device index
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_MODE`
>
> </td>
> <td>
>
>
>
> attr selection mode to configure
>
> </td>
> </tr>
> </tbody>
> </table>

Constants identifying command types for pins uses a `DPLL_CMD_PIN_` prefix and suffix according to command purpose. The pin related attributes use a `DPLL_A_PIN_` prefix and suffix according to attribute purpose.

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
>
> `DPLL_CMD_PIN_ID_GET`
>
> </td>
> <td>
>
>
>
> command to get pin ID
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_MODULE_NAME`
>
> </td>
> <td>
>
>
>
> attr module name of registerer
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_CLOCK_ID`
>
> </td>
> <td>
>
>
>
> attr Unique Clock Identifier (EUI-64), as defined by the IEEE 1588 standard
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_BOARD_LABEL`
>
> </td>
> <td>
>
>
>
> attr pin board label provided by registerer
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_PANEL_LABEL`
>
> </td>
> <td>
>
>
>
> attr pin panel label provided by registerer
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_PACKAGE_LABEL`
>
> </td>
> <td>
>
>
>
> attr pin package label provided by registerer
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_TYPE`
>
> </td>
> <td>
>
>
>
> attr type of a pin
>
> </td>
> </tr>
> </tbody>
> </table>
>
>
> <table>
> <tbody>
> <tr>
> <td>
>
>
>
> `DPLL_CMD_PIN_GET`
>
> </td>
> <td>
>
>
>
> command to get pin info or dump list of available pins
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_ID`
>
> </td>
> <td>
>
>
>
> attr unique a pin ID
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_MODULE_NAME`
>
> </td>
> <td>
>
>
>
> attr module name of registerer
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_CLOCK_ID`
>
> </td>
> <td>
>
>
>
> attr Unique Clock Identifier (EUI-64), as defined by the IEEE 1588 standard
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_BOARD_LABEL`
>
> </td>
> <td>
>
>
>
> attr pin board label provided by registerer
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_PANEL_LABEL`
>
> </td>
> <td>
>
>
>
> attr pin panel label provided by registerer
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_PACKAGE_LABEL`
>
> </td>
> <td>
>
>
>
> attr pin package label provided by registerer
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_TYPE`
>
> </td>
> <td>
>
>
>
> attr type of a pin
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_FREQUENCY`
>
> </td>
> <td>
>
>
>
> attr current frequency of a pin
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_FREQUENCY_SUPPORTED`
>
> </td>
> <td>
>
>
>
> nested attr provides supported frequencies
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_ANY_FREQUENCY_MIN`
>
> </td>
> <td>
>
>
>
> attr minimum value of frequency
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_ANY_FREQUENCY_MAX`
>
> </td>
> <td>
>
>
>
> attr maximum value of frequency
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_PHASE_ADJUST_GRAN`
>
> </td>
> <td>
>
>
>
> attr granularity of phase adjustment value
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_PHASE_ADJUST_MIN`
>
> </td>
> <td>
>
>
>
> attr minimum value of phase adjustment
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_PHASE_ADJUST_MAX`
>
> </td>
> <td>
>
>
>
> attr maximum value of phase adjustment
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_PHASE_ADJUST`
>
> </td>
> <td>
>
>
>
> attr configured value of phase adjustment on parent device
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_PARENT_DEVICE`
>
> </td>
> <td>
>
>
>
> nested attr for each parent device the pin is connected with
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_PARENT_ID`
>
> </td>
> <td>
>
>
>
> attr parent dpll device id
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_PRIO`
>
> </td>
> <td>
>
>
>
> attr priority of pin on the dpll device
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_STATE`
>
> </td>
> <td>
>
>
>
> attr state of pin on the parent dpll device
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_DIRECTION`
>
> </td>
> <td>
>
>
>
> attr direction of a pin on the parent dpll device
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_PHASE_OFFSET`
>
> </td>
> <td>
>
>
>
> attr measured phase difference between a pin and parent dpll
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_PARENT_PIN`
>
> </td>
> <td>
>
>
>
> nested attr for each parent pin the pin is connected with
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_PARENT_ID`
>
> </td>
> <td>
>
>
>
> attr parent pin id
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_STATE`
>
> </td>
> <td>
>
>
>
> attr state of pin on the parent pin
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_CAPABILITIES`
>
> </td>
> <td>
>
>
>
> attr bitmask of pin capabilities
>
> </td>
> </tr>
> </tbody>
> </table>
>
>
> <table>
> <tbody>
> <tr>
> <td>
>
>
>
> `DPLL_CMD_PIN_SET`
>
> </td>
> <td>
>
>
>
> command to set pins configuration
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_ID`
>
> </td>
> <td>
>
>
>
> attr unique a pin ID
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_FREQUENCY`
>
> </td>
> <td>
>
>
>
> attr requested frequency of a pin
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_PHASE_ADJUST`
>
> </td>
> <td>
>
>
>
> attr requested value of phase adjustment on parent device
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_PARENT_DEVICE`
>
> </td>
> <td>
>
>
>
> nested attr for each parent dpll device configuration request
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_PARENT_ID`
>
> </td>
> <td>
>
>
>
> attr parent dpll device id
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_DIRECTION`
>
> </td>
> <td>
>
>
>
> attr requested direction of a pin
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_PRIO`
>
> </td>
> <td>
>
>
>
> attr requested priority of pin on the dpll device
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_STATE`
>
> </td>
> <td>
>
>
>
> attr requested state of pin on the dpll device
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_PARENT_PIN`
>
> </td>
> <td>
>
>
>
> nested attr for each parent pin configuration request
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_PARENT_ID`
>
> </td>
> <td>
>
>
>
> attr parent pin id
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_STATE`
>
> </td>
> <td>
>
>
>
> attr requested state of pin on parent pin
>
> </td>
> </tr>
> </tbody>
> </table>

<a id="rst-netlink-dump-requests"></a>

## Netlink dump requests

The `DPLL_CMD_DEVICE_GET` and `DPLL_CMD_PIN_GET` commands are capable of dump type netlink requests, in which case the response is in the same format as for their `do` request, but every device or pin registered in the system is returned.

<a id="rst-set-commands-format"></a>

## SET commands format

`DPLL_CMD_DEVICE_SET` - to target a dpll device, the user provides `DPLL_A_ID`, which is unique identifier of dpll device in the system, as well as parameter being configured (`DPLL_A_MODE`).

`DPLL_CMD_PIN_SET` - to target a pin user must provide a `DPLL_A_PIN_ID`, which is unique identifier of a pin in the system. Also configured pin parameters must be added. If `DPLL_A_PIN_FREQUENCY` is configured, this affects all the dpll devices that are connected with the pin, that is why frequency attribute shall not be enclosed in `DPLL_A_PIN_PARENT_DEVICE`. Other attributes: `DPLL_A_PIN_PRIO`, `DPLL_A_PIN_STATE` or `DPLL_A_PIN_DIRECTION` must be enclosed in `DPLL_A_PIN_PARENT_DEVICE` as their configuration relates to only one of parent dplls, targeted by `DPLL_A_PIN_PARENT_ID` attribute which is also required inside that nest. For MUX-type pins the `DPLL_A_PIN_STATE` attribute is configured in similar way, by enclosing required state in `DPLL_A_PIN_PARENT_PIN` nested attribute and targeted parent pin id in `DPLL_A_PIN_PARENT_ID`.

In general, it is possible to configure multiple parameters at once, but internally each parameter change will be invoked separately, where order of configuration is not guaranteed by any means.

<a id="rst-configuration-pre-defined-enums"></a>

## Configuration pre-defined enums


#### <a id="c-enum-dpll_mode"></a>`enum dpll_mode`

working modes a dpll can support, differentiates if and how dpll selects one of its inputs to syntonize with it, valid values for DPLL_A_MODE attribute

**Constants**

- `DPLL_MODE_MANUAL`: input can be only selected by sending a request to dpll
- `DPLL_MODE_AUTOMATIC`: highest prio input pin auto selected by dpll

#### <a id="c-enum-dpll_lock_status"></a>`enum dpll_lock_status`

provides information of dpll device lock status, valid values for DPLL_A_LOCK_STATUS attribute

**Constants**

- `DPLL_LOCK_STATUS_UNLOCKED`: dpll was not yet locked to any valid input (or
  forced by setting DPLL_A_MODE to DPLL_MODE_DETACHED)
- `DPLL_LOCK_STATUS_LOCKED`: dpll is locked to a valid signal, but no holdover
  available
- `DPLL_LOCK_STATUS_LOCKED_HO_ACQ`: dpll is locked and holdover acquired
- `DPLL_LOCK_STATUS_HOLDOVER`: dpll is in holdover state - lost a valid lock or
  was forced by disconnecting all the pins (latter possible only when dpll
  lock-state was already DPLL_LOCK_STATUS_LOCKED_HO_ACQ, if dpll lock-state
  was not DPLL_LOCK_STATUS_LOCKED_HO_ACQ, the dpll's lock-state shall remain
  DPLL_LOCK_STATUS_UNLOCKED)

#### <a id="c-enum-dpll_lock_status_error"></a>`enum dpll_lock_status_error`

if previous status change was done due to a failure, this provides information of dpll device lock status error. Valid values for DPLL_A_LOCK_STATUS_ERROR attribute

**Constants**

- `DPLL_LOCK_STATUS_ERROR_NONE`: dpll device lock status was changed without
  any error
- `DPLL_LOCK_STATUS_ERROR_UNDEFINED`: dpll device lock status was changed due
  to undefined error. Driver fills this value up in case it is not able to
  obtain suitable exact error type.
- `DPLL_LOCK_STATUS_ERROR_MEDIA_DOWN`: dpll device lock status was changed
  because of associated media got down. This may happen for example if dpll
  device was previously locked on an input pin of type
  PIN_TYPE_SYNCE_ETH_PORT.
- `DPLL_LOCK_STATUS_ERROR_FRACTIONAL_FREQUENCY_OFFSET_TOO_HIGH`: the FFO
  (Fractional Frequency Offset) between the RX and TX symbol rate on the
  media got too high. This may happen for example if dpll device was
  previously locked on an input pin of type PIN_TYPE_SYNCE_ETH_PORT.

#### <a id="c-enum-dpll_type"></a>`enum dpll_type`

type of dpll, valid values for DPLL_A_TYPE attribute

**Constants**

- `DPLL_TYPE_PPS`: dpll produces Pulse-Per-Second signal
- `DPLL_TYPE_EEC`: dpll drives the Ethernet Equipment Clock

#### <a id="c-enum-dpll_pin_type"></a>`enum dpll_pin_type`

defines possible types of a pin, valid values for DPLL_A_PIN_TYPE attribute

**Constants**

- `DPLL_PIN_TYPE_MUX`: aggregates another layer of selectable pins
- `DPLL_PIN_TYPE_EXT`: external input
- `DPLL_PIN_TYPE_SYNCE_ETH_PORT`: ethernet port PHY's recovered clock
- `DPLL_PIN_TYPE_INT_OSCILLATOR`: device internal oscillator
- `DPLL_PIN_TYPE_GNSS`: GNSS recovered clock

#### <a id="c-enum-dpll_pin_direction"></a>`enum dpll_pin_direction`

defines possible direction of a pin, valid values for DPLL_A_PIN_DIRECTION attribute

**Constants**

- `DPLL_PIN_DIRECTION_INPUT`: pin used as a input of a signal
- `DPLL_PIN_DIRECTION_OUTPUT`: pin used to output the signal

#### <a id="c-enum-dpll_pin_state"></a>`enum dpll_pin_state`

defines possible states of a pin, valid values for DPLL_A_PIN_STATE attribute

**Constants**

- `DPLL_PIN_STATE_CONNECTED`: pin connected, active input of phase locked loop
- `DPLL_PIN_STATE_DISCONNECTED`: pin disconnected, not considered as a valid
  input
- `DPLL_PIN_STATE_SELECTABLE`: pin enabled for automatic input selection

#### <a id="c-enum-dpll_pin_capabilities"></a>`enum dpll_pin_capabilities`

defines possible capabilities of a pin, valid flags on DPLL_A_PIN_CAPABILITIES attribute

**Constants**

- `DPLL_PIN_CAPABILITIES_DIRECTION_CAN_CHANGE`: pin direction can be changed
- `DPLL_PIN_CAPABILITIES_PRIORITY_CAN_CHANGE`: pin priority can be changed
- `DPLL_PIN_CAPABILITIES_STATE_CAN_CHANGE`: pin state can be changed

#### <a id="c-enum-dpll_feature_state"></a>`enum dpll_feature_state`

Allow control (enable/disable) and status checking over features.

**Constants**

- `DPLL_FEATURE_STATE_DISABLE`: feature shall be disabled
- `DPLL_FEATURE_STATE_ENABLE`: feature shall be enabled


<a id="rst-notifications"></a>

## Notifications

dpll device can provide notifications regarding status changes of the device, i.e. lock status changes, input/output changes or other alarms. There is one multicast group that is used to notify user-space apps via netlink socket: `DPLL_MCGRP_MONITOR`

Notifications messages:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
>
> `DPLL_CMD_DEVICE_CREATE_NTF`
>
> </td>
> <td>
>
>
>
> dpll device was created
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_CMD_DEVICE_DELETE_NTF`
>
> </td>
> <td>
>
>
>
> dpll device was deleted
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_CMD_DEVICE_CHANGE_NTF`
>
> </td>
> <td>
>
>
>
> dpll device has changed
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_CMD_PIN_CREATE_NTF`
>
> </td>
> <td>
>
>
>
> dpll pin was created
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_CMD_PIN_DELETE_NTF`
>
> </td>
> <td>
>
>
>
> dpll pin was deleted
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_CMD_PIN_CHANGE_NTF`
>
> </td>
> <td>
>
>
>
> dpll pin has changed
>
> </td>
> </tr>
> </tbody>
> </table>

Events format is the same as for the corresponding get command. Format of `DPLL_CMD_DEVICE_` events is the same as response of `DPLL_CMD_DEVICE_GET`. Format of `DPLL_CMD_PIN_` events is same as response of `DPLL_CMD_PIN_GET`.

<a id="rst-device-driver-implementation"></a>

## Device driver implementation

Device is allocated by dpll\_device\_get() call. Second call with the same arguments will not create new object but provides pointer to previously created device for given arguments, it also increases refcount of that object. Device is deallocated by dpll\_device\_put() call, which first decreases the refcount, once refcount is cleared the object is destroyed.

Device should implement set of operations and register device via dpll\_device\_register() at which point it becomes available to the users. Multiple driver instances can obtain reference to it with dpll\_device\_get(), as well as register dpll device with their own ops and priv.

The pins are allocated separately with dpll\_pin\_get(), it works similarly to dpll\_device\_get(). Function first creates object and then for each call with the same arguments only the object refcount increases. Also dpll\_pin\_put() works similarly to dpll\_device\_put().

A pin can be registered with parent dpll device or parent pin, depending on hardware needs. Each registration requires registerer to provide set of pin callbacks, and private data pointer for calling them:

- dpll\_pin\_register() - register pin with a dpll device,

- dpll\_pin\_on\_pin\_register() - register pin with another MUX type pin.

Notifications of adding or removing dpll devices are created within subsystem itself. Notifications about registering/deregistering pins are also invoked by the subsystem. Notifications about status changes either of dpll device or a pin are invoked in two ways:

- after successful change was requested on dpll subsystem, the subsystem calls corresponding notification,

- requested by device driver with dpll\_device\_change\_ntf() or dpll\_pin\_change\_ntf() when driver informs about the status change.

The device driver using dpll interface is not required to implement all the callback operation. Nevertheless, there are few required to be implemented. Required dpll device level callback operations:

- `.mode_get`,

- `.lock_status_get`.

Required pin level callback operations:

- `.state_on_dpll_get` (pins registered with dpll device),

- `.state_on_pin_get` (pins registered with parent pin),

- `.direction_get`.

Every other operation handler is checked for existence and `-EOPNOTSUPP` is returned in case of absence of specific handler.

The simplest implementation is in the OCP TimeCard driver. The ops structures are defined like this:



```c
static const struct dpll_device_ops dpll_ops = {
        .lock_status_get = ptp_ocp_dpll_lock_status_get,
        .mode_get = ptp_ocp_dpll_mode_get,
        .mode_supported = ptp_ocp_dpll_mode_supported,
};

static const struct dpll_pin_ops dpll_pins_ops = {
        .frequency_get = ptp_ocp_dpll_frequency_get,
        .frequency_set = ptp_ocp_dpll_frequency_set,
        .direction_get = ptp_ocp_dpll_direction_get,
        .direction_set = ptp_ocp_dpll_direction_set,
        .state_on_dpll_get = ptp_ocp_dpll_state_get,
};
```

The registration part is then looks like this part:



```c
clkid = pci_get_dsn(pdev);
bp->dpll = dpll_device_get(clkid, 0, THIS_MODULE);
if (IS_ERR(bp->dpll)) {
        err = PTR_ERR(bp->dpll);
        dev_err(&pdev->dev, "dpll_device_alloc failed\n");
        goto out;
}

err = dpll_device_register(bp->dpll, DPLL_TYPE_PPS, &dpll_ops, bp);
if (err)
        goto out;

for (i = 0; i < OCP_SMA_NUM; i++) {
        bp->sma[i].dpll_pin = dpll_pin_get(clkid, i, THIS_MODULE, &bp->sma[i].dpll_prop);
        if (IS_ERR(bp->sma[i].dpll_pin)) {
                err = PTR_ERR(bp->dpll);
                goto out_dpll;
        }

        err = dpll_pin_register(bp->dpll, bp->sma[i].dpll_pin, &dpll_pins_ops,
                                &bp->sma[i]);
        if (err) {
                dpll_pin_put(bp->sma[i].dpll_pin);
                goto out_dpll;
        }
}
```

In the error path we have to rewind every allocation in the reverse order:



```c
while (i) {
        --i;
        dpll_pin_unregister(bp->dpll, bp->sma[i].dpll_pin, &dpll_pins_ops, &bp->sma[i]);
        dpll_pin_put(bp->sma[i].dpll_pin);
}
dpll_device_put(bp->dpll);
```

More complex example can be found in Intel's ICE driver or nVidia's mlx5 driver.

<a id="rst-synce-enablement"></a>

## SyncE enablement

For SyncE enablement it is required to allow control over dpll device for a software application which monitors and configures the inputs of dpll device in response to current state of a dpll device and its inputs. In such scenario, dpll device input signal shall be also configurable to drive dpll with signal recovered from the PHY netdevice. This is done by exposing a pin to the netdevice - attaching pin to the netdevice itself with `dpll_netdev_pin_set(struct net_device *dev, struct dpll_pin *dpll_pin)`. Exposed pin id handle `DPLL_A_PIN_ID` is then identifiable by the user as it is attached to rtnetlink respond to get `RTM_NEWLINK` command in nested attribute `IFLA_DPLL_PIN`.

---

# Error Detection And Correction (EDAC) Devices

_Peios Kernel / Hardware and drivers / Driver development / Clocks, signals and platform services_

> There are several things to be aware of that aren't at all obvious, like sockets, *socket sets, banks, rows, chip-select rows, channels, etc...

<a id="rst-error-detection-and-correction-edac-devices"></a>

<a id="rst-main-concepts-used-at-the-edac-subsystem"></a>

## Main Concepts used at the EDAC subsystem

There are several things to be aware of that aren't at all obvious, like *sockets, \*socket sets*, *banks*, *rows*, *chip-select rows*, *channels*, etc...

These are some of the many terms that are thrown about that don't always mean what people think they mean (Inconceivable\!).  In the interest of creating a common ground for discussion, terms and their definitions will be established.

- Memory devices

The individual DRAM chips on a memory stick.  These devices commonly output 4 and 8 bits each (x4, x8). Grouping several of these in parallel provides the number of bits that the memory controller expects: typically 72 bits, in order to provide 64 bits + 8 bits of ECC data.

- Memory Stick

A printed circuit board that aggregates multiple memory devices in parallel.  In general, this is the Field Replaceable Unit (FRU) which gets replaced, in the case of excessive errors. Most often it is also called DIMM (Dual Inline Memory Module).

- Memory Socket

A physical connector on the motherboard that accepts a single memory stick. Also called as "slot" on several datasheets.

- Channel

A memory controller channel, responsible to communicate with a group of DIMMs. Each channel has its own independent control (command) and data bus, and can be used independently or grouped with other channels.

- Branch

It is typically the highest hierarchy on a Fully-Buffered DIMM memory controller. Typically, it contains two channels. Two channels at the same branch can be used in single mode or in lockstep mode. When lockstep is enabled, the cacheline is doubled, but it generally brings some performance penalty. Also, it is generally not possible to point to just one memory stick when an error occurs, as the error correction code is calculated using two DIMMs instead of one. Due to that, it is capable of correcting more errors than on single mode.

- Single-channel

The data accessed by the memory controller is contained into one dimm only. E. g. if the data is 64 bits-wide, the data flows to the CPU using one 64 bits parallel access. Typically used with SDR, DDR, DDR2 and DDR3 memories. FB-DIMM and RAMBUS use a different concept for channel, so this concept doesn't apply there.

- Double-channel

The data size accessed by the memory controller is interlaced into two dimms, accessed at the same time. E. g. if the DIMM is 64 bits-wide (72 bits with ECC), the data flows to the CPU using a 128 bits parallel access.

- Chip-select row

This is the name of the DRAM signal used to select the DRAM ranks to be accessed. Common chip-select rows for single channel are 64 bits, for dual channel 128 bits. It may not be visible by the memory controller, as some DIMM types have a memory buffer that can hide direct access to it from the Memory Controller.

- Single-Ranked stick

A Single-ranked stick has 1 chip-select row of memory. Motherboards commonly drive two chip-select pins to a memory stick. A single-ranked stick, will occupy only one of those rows. The other will be unused.

<a id="rst-doubleranked"></a>

- Double-Ranked stick

A double-ranked stick has two chip-select rows which access different sets of memory devices.  The two rows cannot be accessed concurrently.

- Double-sided stick

**DEPRECATED TERM**, see [Double-Ranked stick](<#rst-doubleranked>).

A double-sided stick has two chip-select rows which access different sets of memory devices. The two rows cannot be accessed concurrently. "Double-sided" is irrespective of the memory devices being mounted on both sides of the memory stick.

- Socket set

All of the memory sticks that are required for a single memory access or all of the memory sticks spanned by a chip-select row.  A single socket set has two chip-select rows and if double-sided sticks are used these will occupy those chip-select rows.

- Bank

This term is avoided because it is unclear when needing to distinguish between chip-select rows and socket sets.

- High Bandwidth Memory (HBM)

HBM is a new memory type with low power consumption and ultra-wide communication lanes. It uses vertically stacked memory chips (DRAM dies) interconnected by microscopic wires called "through-silicon vias," or TSVs.

Several stacks of HBM chips connect to the CPU or GPU through an ultra-fast interconnect called the "interposer". Therefore, HBM's characteristics are nearly indistinguishable from on-chip integrated RAM.

<a id="rst-memory-controllers"></a>

## Memory Controllers

Most of the EDAC core is focused on doing Memory Controller error detection. The `edac_mc_alloc()`. It uses internally the struct `mem_ctl_info` to describe the memory controllers, with is an opaque struct for the EDAC drivers. Only the EDAC core is allowed to touch it.


#### <a id="c-enum-dev_type"></a>`enum dev_type`

describe the type of memory DRAM chips used at the stick

**Constants**

- `DEV_UNKNOWN`: Can't be determined, or MC doesn't support detect it
- `DEV_X1`: 1 bit for data
- `DEV_X2`: 2 bits for data
- `DEV_X4`: 4 bits for data
- `DEV_X8`: 8 bits for data
- `DEV_X16`: 16 bits for data
- `DEV_X32`: 32 bits for data
- `DEV_X64`: 64 bits for data

**Description**

Typical values are x4 and x8.

#### <a id="c-enum-hw_event_mc_err_type"></a>`enum hw_event_mc_err_type`

type of the detected error

**Constants**

- `HW_EVENT_ERR_CORRECTED`: Corrected Error - Indicates that an ECC
  corrected error was detected
- `HW_EVENT_ERR_UNCORRECTED`: Uncorrected Error - Indicates an error that
  can't be corrected by ECC, but it is not
  fatal (maybe it is on an unused memory area,
  or the memory controller could recover from
  it for example, by re-trying the operation).
- `HW_EVENT_ERR_DEFERRED`: Deferred Error - Indicates an uncorrectable
  error whose handling is not urgent. This could
  be due to hardware data poisoning where the
  system can continue operation until the poisoned
  data is consumed. Preemptive measures may also
  be taken, e.g. offlining pages, etc.
- `HW_EVENT_ERR_FATAL`: Fatal Error - Uncorrected error that could not
  be recovered.
- `HW_EVENT_ERR_INFO`: Informational - The CPER spec defines a forth
  type of error: informational logs.

#### <a id="c-enum-mem_type"></a>`enum mem_type`

memory types. For a more detailed reference, please see http://en.wikipedia.org/wiki/DRAM

**Constants**

- `MEM_EMPTY`: Empty csrow
- `MEM_RESERVED`: Reserved csrow type
- `MEM_UNKNOWN`: Unknown csrow type
- `MEM_FPM`: FPM - Fast Page Mode, used on systems up to 1995.
- `MEM_EDO`: EDO - Extended data out, used on systems up to 1998.
- `MEM_BEDO`: BEDO - Burst Extended data out, an EDO variant.
- `MEM_SDR`: SDR - Single data rate SDRAM
  http://en.wikipedia.org/wiki/Synchronous_dynamic_random-access_memory
  They use 3 pins for chip select: Pins 0 and 2 are
  for rank 0; pins 1 and 3 are for rank 1, if the memory
  is dual-rank.
- `MEM_RDR`: Registered SDR SDRAM
- `MEM_DDR`: Double data rate SDRAM
  http://en.wikipedia.org/wiki/DDR_SDRAM
- `MEM_RDDR`: Registered Double data rate SDRAM
  This is a variant of the DDR memories.
  A registered memory has a buffer inside it, hiding
  part of the memory details to the memory controller.
- `MEM_RMBS`: Rambus DRAM, used on a few Pentium III/IV controllers.
- `MEM_DDR2`: DDR2 RAM, as described at JEDEC JESD79-2F.
  Those memories are labeled as "PC2-" instead of "PC" to
  differentiate from DDR.
- `MEM_FB_DDR2`: Fully-Buffered DDR2, as described at JEDEC Std No. 205
  and JESD206.
  Those memories are accessed per DIMM slot, and not by
  a chip select signal.
- `MEM_RDDR2`: Registered DDR2 RAM
  This is a variant of the DDR2 memories.
- `MEM_XDR`: Rambus XDR
  It is an evolution of the original RAMBUS memories,
  created to compete with DDR2. Weren't used on any
  x86 arch, but cell_edac PPC memory controller uses it.
- `MEM_DDR3`: DDR3 RAM
- `MEM_RDDR3`: Registered DDR3 RAM
  This is a variant of the DDR3 memories.
- `MEM_LRDDR3`: Load-Reduced DDR3 memory.
- `MEM_LPDDR3`: Low-Power DDR3 memory.
- `MEM_DDR4`: Unbuffered DDR4 RAM
- `MEM_RDDR4`: Registered DDR4 RAM
  This is a variant of the DDR4 memories.
- `MEM_LRDDR4`: Load-Reduced DDR4 memory.
- `MEM_LPDDR4`: Low-Power DDR4 memory.
- `MEM_DDR5`: Unbuffered DDR5 RAM
- `MEM_RDDR5`: Registered DDR5 RAM
- `MEM_LRDDR5`: Load-Reduced DDR5 memory.
- `MEM_NVDIMM`: Non-volatile RAM
- `MEM_WIO2`: Wide I/O 2.
- `MEM_HBM2`: High bandwidth Memory Gen 2.
- `MEM_HBM3`: High bandwidth Memory Gen 3.

#### <a id="c-enum-edac_type"></a>`enum edac_type`

Error Detection and Correction capabilities and mode

**Constants**

- `EDAC_UNKNOWN`: Unknown if ECC is available
- `EDAC_NONE`: Doesn't support ECC
- `EDAC_RESERVED`: Reserved ECC type
- `EDAC_PARITY`: Detects parity errors
- `EDAC_EC`: Error Checking - no correction
- `EDAC_SECDED`: Single bit error correction, Double detection
- `EDAC_S2ECD2ED`: Chipkill x2 devices - do these exist?
- `EDAC_S4ECD4ED`: Chipkill x4 devices
- `EDAC_S8ECD8ED`: Chipkill x8 devices
- `EDAC_S16ECD16ED`: Chipkill x16 devices

#### <a id="c-enum-scrub_type"></a>`enum scrub_type`

scrubbing capabilities

**Constants**

- `SCRUB_UNKNOWN`: Unknown if scrubber is available
- `SCRUB_NONE`: No scrubber
- `SCRUB_SW_PROG`: SW progressive (sequential) scrubbing
- `SCRUB_SW_SRC`: Software scrub only errors
- `SCRUB_SW_PROG_SRC`: Progressive software scrub from an error
- `SCRUB_SW_TUNABLE`: Software scrub frequency is tunable
- `SCRUB_HW_PROG`: HW progressive (sequential) scrubbing
- `SCRUB_HW_SRC`: Hardware scrub only errors
- `SCRUB_HW_PROG_SRC`: Progressive hardware scrub from an error
- `SCRUB_HW_TUNABLE`: Hardware scrub frequency is tunable

#### <a id="c-enum-edac_mc_layer_type"></a>`enum edac_mc_layer_type`

memory controller hierarchy layer

**Constants**

- `EDAC_MC_LAYER_BRANCH`: memory layer is named "branch"
- `EDAC_MC_LAYER_CHANNEL`: memory layer is named "channel"
- `EDAC_MC_LAYER_SLOT`: memory layer is named "slot"
- `EDAC_MC_LAYER_CHIP_SELECT`: memory layer is named "chip select"
- `EDAC_MC_LAYER_ALL_MEM`: memory layout is unknown. All memory is mapped
  as a single memory area. This is used when
  retrieving errors from a firmware driven driver.

**Description**

This enum is used by the drivers to tell edac_mc_sysfs what name should
be used when describing a memory stick location.

#### <a id="c-struct-edac_mc_layer"></a>`struct edac_mc_layer`

describes the memory controller hierarchy

**Definition**

```c
struct edac_mc_layer {
    enum edac_mc_layer_type type;
    unsigned size;
    bool is_virt_csrow;
};
```

**Members**

- `type`: layer type
- `size`: number of components per layer. For example,
  if the channel layer has two channels, size = 2
- `is_virt_csrow`: This layer is part of the "csrow" when old API
  compatibility mode is enabled. Otherwise, it is
  a channel

#### <a id="c-struct-rank_info"></a>`struct rank_info`

contains the information for one DIMM rank

**Definition**

```c
struct rank_info {
    int chan_idx;
    struct csrow_info *csrow;
    struct dimm_info *dimm;
    u32 ce_count;
};
```

**Members**

- `chan_idx`: channel number where the rank is (typically, 0 or 1)
- `csrow`: A pointer to the chip select row structure (the parent
  structure). The location of the rank is given by
  the (csrow->csrow_idx, chan_idx) vector.
- `dimm`: A pointer to the DIMM structure, where the DIMM label
  information is stored.
- `ce_count`: number of correctable errors for this rank

**Description**

- FIXME: Currently, the EDAC core model will assume one DIMM per rank.

  This is a bad assumption, but it makes this patch easier. Later
  patches in this series will fix this issue.

#### <a id="c-struct-edac_raw_error_desc"></a>`struct edac_raw_error_desc`

Raw error report structure

**Definition**

```c
struct edac_raw_error_desc {
    char location[LOCATION_SIZE];
    char label[(EDAC_MC_LABEL_LEN + 1 + sizeof(OTHER_LABEL)) * EDAC_MAX_LABELS];
    long grain;
    u16 error_count;
    enum hw_event_mc_err_type type;
    int top_layer;
    int mid_layer;
    int low_layer;
    unsigned long page_frame_number;
    unsigned long offset_in_page;
    unsigned long syndrome;
    const char *msg;
    const char *other_detail;
};
```

**Members**

- `location`: location of the error
- `label`: label of the affected DIMM(s)
- `grain`: minimum granularity for an error report, in bytes
- `error_count`: number of errors of the same type
- `type`: severity of the error (CE/UE/Fatal)
- `top_layer`: top layer of the error (layer\[0\])
- `mid_layer`: middle layer of the error (layer\[1\])
- `low_layer`: low layer of the error (layer\[2\])
- `page_frame_number`: page where the error happened
- `offset_in_page`: page offset
- `syndrome`: syndrome of the error (or 0 if unknown or if
  the syndrome is not applicable)
- `msg`: error message
- `other_detail`: other driver-specific detail about the error

#### <a id="c-edac_get_dimm"></a>`edac_get_dimm()`

```c
struct dimm_info * edac_get_dimm(struct mem_ctl_info *mci, int layer0, int layer1, int layer2)
```

Get DIMM info from a memory controller given by \[layer0,layer1,layer2\] position

**Parameters**

- `struct mem_ctl_info *mci`: MC descriptor struct mem_ctl_info
- `int layer0`: layer0 position
- `int layer1`: layer1 position. Unused if n_layers \< 2
- `int layer2`: layer2 position. Unused if n_layers \< 3

**Description**

For 1 layer, this function returns "dimms\[layer0\]";

For 2 layers, this function is similar to allocating a two-dimensional
array and returning "dimms\[layer0\]\[layer1\]";

For 3 layers, this function is similar to allocating a tri-dimensional
array and returning "dimms\[layer0\]\[layer1\]\[layer2\]";

#### <a id="c-struct-edac_scrub_ops"></a>`struct edac_scrub_ops`

scrub device operations (all elements optional)

**Definition**

```c
struct edac_scrub_ops {
    int (*read_addr)(struct device *dev, void *drv_data, u64 *base);
    int (*read_size)(struct device *dev, void *drv_data, u64 *size);
    int (*write_addr)(struct device *dev, void *drv_data, u64 base);
    int (*write_size)(struct device *dev, void *drv_data, u64 size);
    int (*get_enabled_bg)(struct device *dev, void *drv_data, bool *enable);
    int (*set_enabled_bg)(struct device *dev, void *drv_data, bool enable);
    int (*get_min_cycle)(struct device *dev, void *drv_data,  u32 *min);
    int (*get_max_cycle)(struct device *dev, void *drv_data,  u32 *max);
    int (*get_cycle_duration)(struct device *dev, void *drv_data, u32 *cycle);
    int (*set_cycle_duration)(struct device *dev, void *drv_data, u32 cycle);
};
```

**Members**

- `read_addr`: read base address of scrubbing range.
- `read_size`: read offset of scrubbing range.
- `write_addr`: set base address of the scrubbing range.
- `write_size`: set offset of the scrubbing range.
- `get_enabled_bg`: check if currently performing background scrub.
- `set_enabled_bg`: start or stop a bg-scrub.
- `get_min_cycle`: get minimum supported scrub cycle duration in seconds.
- `get_max_cycle`: get maximum supported scrub cycle duration in seconds.
- `get_cycle_duration`: get current scrub cycle duration in seconds.
- `set_cycle_duration`: set current scrub cycle duration in seconds.

#### <a id="c-struct-edac_ecs_ops"></a>`struct edac_ecs_ops`

ECS device operations (all elements optional)

**Definition**

```c
struct edac_ecs_ops {
    int (*get_log_entry_type)(struct device *dev, void *drv_data, int fru_id, u32 *val);
    int (*set_log_entry_type)(struct device *dev, void *drv_data, int fru_id, u32 val);
    int (*get_mode)(struct device *dev, void *drv_data, int fru_id, u32 *val);
    int (*set_mode)(struct device *dev, void *drv_data, int fru_id, u32 val);
    int (*reset)(struct device *dev, void *drv_data, int fru_id, u32 val);
    int (*get_threshold)(struct device *dev, void *drv_data, int fru_id, u32 *threshold);
    int (*set_threshold)(struct device *dev, void *drv_data, int fru_id, u32 threshold);
};
```

**Members**

- `get_log_entry_type`: read the log entry type value.
- `set_log_entry_type`: set the log entry type value.
- `get_mode`: read the mode value.
- `set_mode`: set the mode value.
- `reset`: reset the ECS counter.
- `get_threshold`: read the threshold count per gigabits of memory cells.
- `set_threshold`: set the threshold count per gigabits of memory cells.

#### <a id="c-struct-edac_mem_repair_ops"></a>`struct edac_mem_repair_ops`

memory repair operations (all elements are optional except do_repair, set_hpa/set_dpa)

**Definition**

```c
struct edac_mem_repair_ops {
    int (*get_repair_type)(struct device *dev, void *drv_data, const char **type);
    int (*get_persist_mode)(struct device *dev, void *drv_data, bool *persist);
    int (*set_persist_mode)(struct device *dev, void *drv_data, bool persist);
    int (*get_repair_safe_when_in_use)(struct device *dev, void *drv_data, bool *safe);
    int (*get_hpa)(struct device *dev, void *drv_data, u64 *hpa);
    int (*set_hpa)(struct device *dev, void *drv_data, u64 hpa);
    int (*get_min_hpa)(struct device *dev, void *drv_data, u64 *hpa);
    int (*get_max_hpa)(struct device *dev, void *drv_data, u64 *hpa);
    int (*get_dpa)(struct device *dev, void *drv_data, u64 *dpa);
    int (*set_dpa)(struct device *dev, void *drv_data, u64 dpa);
    int (*get_min_dpa)(struct device *dev, void *drv_data, u64 *dpa);
    int (*get_max_dpa)(struct device *dev, void *drv_data, u64 *dpa);
    int (*get_nibble_mask)(struct device *dev, void *drv_data, u32 *val);
    int (*set_nibble_mask)(struct device *dev, void *drv_data, u32 val);
    int (*get_bank_group)(struct device *dev, void *drv_data, u32 *val);
    int (*set_bank_group)(struct device *dev, void *drv_data, u32 val);
    int (*get_bank)(struct device *dev, void *drv_data, u32 *val);
    int (*set_bank)(struct device *dev, void *drv_data, u32 val);
    int (*get_rank)(struct device *dev, void *drv_data, u32 *val);
    int (*set_rank)(struct device *dev, void *drv_data, u32 val);
    int (*get_row)(struct device *dev, void *drv_data, u32 *val);
    int (*set_row)(struct device *dev, void *drv_data, u32 val);
    int (*get_column)(struct device *dev, void *drv_data, u32 *val);
    int (*set_column)(struct device *dev, void *drv_data, u32 val);
    int (*get_channel)(struct device *dev, void *drv_data, u32 *val);
    int (*set_channel)(struct device *dev, void *drv_data, u32 val);
    int (*get_sub_channel)(struct device *dev, void *drv_data, u32 *val);
    int (*set_sub_channel)(struct device *dev, void *drv_data, u32 val);
    int (*do_repair)(struct device *dev, void *drv_data, u32 val);
};
```

**Members**

- `get_repair_type`: get the memory repair type, listed in
  enum edac_mem_repair_function.
- `get_persist_mode`: get the current persist mode.
  false - Soft repair type (temporary repair).
  true - Hard memory repair type (permanent repair).
- `set_persist_mode`: set the persist mode of the memory repair instance.
- `get_repair_safe_when_in_use`: get whether memory media is accessible and
  data is retained during repair operation.
- `get_hpa`: get current host physical address (HPA) of memory to repair.
- `set_hpa`: set host physical address (HPA) of memory to repair.
- `get_min_hpa`: get the minimum supported host physical address (HPA).
- `get_max_hpa`: get the maximum supported host physical address (HPA).
- `get_dpa`: get current device physical address (DPA) of memory to repair.
- `set_dpa`: set device physical address (DPA) of memory to repair.
  In some states of system configuration (e.g. before address decoders
  have been configured), memory devices (e.g. CXL) may not have an active
  mapping in the host physical address map. As such, the memory
  to repair must be identified by a device specific physical addressing
  scheme using a device physical address(DPA). The DPA and other control
  attributes to use for the repair operations will be presented in related
  error records.
- `get_min_dpa`: get the minimum supported device physical address (DPA).
- `get_max_dpa`: get the maximum supported device physical address (DPA).
- `get_nibble_mask`: get current nibble mask of memory to repair.
- `set_nibble_mask`: set nibble mask of memory to repair.
- `get_bank_group`: get current bank group of memory to repair.
- `set_bank_group`: set bank group of memory to repair.
- `get_bank`: get current bank of memory to repair.
- `set_bank`: set bank of memory to repair.
- `get_rank`: get current rank of memory to repair.
- `set_rank`: set rank of memory to repair.
- `get_row`: get current row of memory to repair.
- `set_row`: set row of memory to repair.
- `get_column`: get current column of memory to repair.
- `set_column`: set column of memory to repair.
- `get_channel`: get current channel of memory to repair.
- `set_channel`: set channel of memory to repair.
- `get_sub_channel`: get current subchannel of memory to repair.
- `set_sub_channel`: set subchannel of memory to repair.
- `do_repair`: Issue memory repair operation for the HPA/DPA and
  other control attributes set for the memory to repair.

**Description**

All elements are optional except do_repair and at least one of set_hpa/set_dpa.



#### <a id="c-edac_mc_alloc"></a>`edac_mc_alloc()`

```c
struct mem_ctl_info * edac_mc_alloc(unsigned int mc_num, unsigned int n_layers, struct edac_mc_layer *layers, unsigned int sz_pvt)
```

Allocate and partially fill a struct `mem_ctl_info`.

**Parameters**

- `unsigned int mc_num`: Memory controller number
- `unsigned int n_layers`: Number of MC hierarchy layers
- `struct edac_mc_layer *layers`: Describes each layer as seen by the Memory Controller
- `unsigned int sz_pvt`: size of private storage needed

**Description**

Everything is kmalloc'ed as one big chunk - more efficient.
Only can be used if all structures have the same lifetime - otherwise
you have to allocate and initialize your own structures.

Use [`edac_mc_free()`](#c-edac_mc_free) to free mc structures allocated by this function.

> [!NOTE]
> drivers handle multi-rank memories in different ways: in some
> drivers, one multi-rank memory stick is mapped as one entry, while, in
> others, a single multi-rank memory stick would be mapped into several
> entries. Currently, this function will allocate multiple struct dimm_info
> on such scenarios, as grouping the multiple ranks require drivers change.

**Return**

On success, return a pointer to struct mem_ctl_info pointer;
`NULL` otherwise

#### <a id="c-edac_get_owner"></a>`edac_get_owner()`

```c
const char * edac_get_owner(void)
```

Return the owner's mod_name of EDAC MC

**Parameters**

- `void`: no arguments

**Return**

Pointer to mod_name string when EDAC MC is owned. NULL otherwise.

#### <a id="c-edac_mc_free"></a>`edac_mc_free()`

```c
void edac_mc_free(struct mem_ctl_info *mci)
```

Frees a previously allocated **mci** structure

**Parameters**

- `struct mem_ctl_info *mci`: pointer to a struct mem_ctl_info structure

#### <a id="c-edac_has_mcs"></a>`edac_has_mcs()`

```c
bool edac_has_mcs(void)
```

Check if any MCs have been allocated.

**Parameters**

- `void`: no arguments

**Return**

True if MC instances have been registered successfully.
False otherwise.

#### <a id="c-edac_mc_find"></a>`edac_mc_find()`

```c
struct mem_ctl_info * edac_mc_find(int idx)
```

Search for a mem_ctl_info structure whose index is **idx**.

**Parameters**

- `int idx`: index to be seek

**Description**

If found, return a pointer to the structure.
Else return NULL.

#### <a id="c-find_mci_by_dev"></a>`find_mci_by_dev()`

```c
struct mem_ctl_info * find_mci_by_dev(struct device *dev)
```

Scan list of controllers looking for the one that manages the **dev** device.

**Parameters**

- `struct device *dev`: pointer to a struct device related with the MCI

**Return**

on success, returns a pointer to struct `mem_ctl_info`;
`NULL` otherwise.

#### <a id="c-edac_mc_del_mc"></a>`edac_mc_del_mc()`

```c
struct mem_ctl_info * edac_mc_del_mc(struct device *dev)
```

Remove sysfs entries for mci structure associated with **dev** and remove mci structure from global list.

**Parameters**

- `struct device *dev`: Pointer to struct [`device`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-struct-device) representing mci structure to remove.

**Return**

pointer to removed mci structure, or `NULL` if device not found.

#### <a id="c-edac_mc_find_csrow_by_page"></a>`edac_mc_find_csrow_by_page()`

```c
int edac_mc_find_csrow_by_page(struct mem_ctl_info *mci, unsigned long page)
```

Ancillary routine to identify what csrow contains a memory page.

**Parameters**

- `struct mem_ctl_info *mci`: pointer to a struct mem_ctl_info structure
- `unsigned long page`: memory page to find

**Return**

on success, returns the csrow. -1 if not found.

#### <a id="c-edac_raw_mc_handle_error"></a>`edac_raw_mc_handle_error()`

```c
void edac_raw_mc_handle_error(struct edac_raw_error_desc *e)
```

Reports a memory event to userspace without doing anything to discover the error location.

**Parameters**

- `struct edac_raw_error_desc *e`: error description

**Description**

This raw function is used internally by [`edac_mc_handle_error()`](#c-edac_mc_handle_error). It should
only be called directly when the hardware error come directly from BIOS,
like in the case of APEI GHES driver.

#### <a id="c-edac_mc_handle_error"></a>`edac_mc_handle_error()`

```c
void edac_mc_handle_error(const enum hw_event_mc_err_type type, struct mem_ctl_info *mci, const u16 error_count, const unsigned long page_frame_number, const unsigned long offset_in_page, const unsigned long syndrome, const int top_layer, const int mid_layer, const int low_layer, const char *msg, const char *other_detail)
```

Reports a memory event to userspace.

**Parameters**

- `const enum hw_event_mc_err_type type`: severity of the error (CE/UE/Fatal)
- `struct mem_ctl_info *mci`: a struct mem_ctl_info pointer
- `const u16 error_count`: Number of errors of the same type
- `const unsigned long page_frame_number`: mem page where the error occurred
- `const unsigned long offset_in_page`: offset of the error inside the page
- `const unsigned long syndrome`: ECC syndrome
- `const int top_layer`: Memory layer\[0\] position
- `const int mid_layer`: Memory layer\[1\] position
- `const int low_layer`: Memory layer\[2\] position
- `const char *msg`: Message meaningful to the end users that
  explains the event
- `const char *other_detail`: Technical details about the event that
  may help hardware manufacturers and
  EDAC developers to analyse the event


<a id="rst-pci-controllers"></a>

## PCI Controllers

The EDAC subsystem provides a mechanism to handle PCI controllers by calling the `edac_pci_alloc_ctl_info()`. It will use the struct `edac_pci_ctl_info` to describe the PCI controllers.


#### <a id="c-edac_pci_alloc_ctl_info"></a>`edac_pci_alloc_ctl_info()`

```c
struct edac_pci_ctl_info * edac_pci_alloc_ctl_info(unsigned int sz_pvt, const char *edac_pci_name)
```

The `alloc()` function for the 'edac_pci' control info structure.

**Parameters**

- `unsigned int sz_pvt`: size of the private info at struct `edac_pci_ctl_info`
- `const char *edac_pci_name`: name of the PCI device

**Description**

The chip driver will allocate one of these for each
edac_pci it is going to control/register with the EDAC CORE.

**Return**

a pointer to struct `edac_pci_ctl_info` on success; `NULL` otherwise.

#### <a id="c-edac_pci_free_ctl_info"></a>`edac_pci_free_ctl_info()`

```c
void edac_pci_free_ctl_info(struct edac_pci_ctl_info *pci)
```

Last action on the pci control structure.

**Parameters**

- `struct edac_pci_ctl_info *pci`: pointer to struct `edac_pci_ctl_info`

**Description**

Calls the remove sysfs information, which will unregister
this control struct's kobj. When that kobj's ref count
goes to zero, its release function will be call and then
[`kfree()`](/kernel/internals/core-api/mm-api.md#c-kfree) the memory.

#### <a id="c-edac_pci_alloc_index"></a>`edac_pci_alloc_index()`

```c
int edac_pci_alloc_index(void)
```

Allocate a unique PCI index number

**Parameters**

- `void`: no arguments

**Return**

allocated index number

#### <a id="c-edac_pci_add_device"></a>`edac_pci_add_device()`

```c
int edac_pci_add_device(struct edac_pci_ctl_info *pci, int edac_idx)
```

Insert the 'edac_dev' structure into the edac_pci global list and create sysfs entries associated with edac_pci structure.

**Parameters**

- `struct edac_pci_ctl_info *pci`: pointer to the edac_device structure to be added to the list
- `int edac_idx`: A unique numeric identifier to be assigned to the
  'edac_pci' structure.

**Return**

0 on Success, or an error code on failure

#### <a id="c-edac_pci_del_device"></a>`edac_pci_del_device()`

```c
struct edac_pci_ctl_info * edac_pci_del_device(struct device *dev)
```

**Parameters**

- `struct device *dev`: Pointer to 'struct device' representing edac_pci structure
  to remove

**Description**

Remove sysfs entries for specified edac_pci structure and
then remove edac_pci structure from global list

**Return**

Pointer to removed edac_pci structure,
or `NULL` if device not found

#### <a id="c-edac_pci_create_generic_ctl"></a>`edac_pci_create_generic_ctl()`

```c
struct edac_pci_ctl_info * edac_pci_create_generic_ctl(struct device *dev, const char *mod_name)
```

**Parameters**

- `struct device *dev`: pointer to struct [`device`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-struct-device);
- `const char *mod_name`: name of the PCI device

**Description**

A generic constructor for a PCI parity polling device
Some systems have more than one domain of PCI busses.
For systems with one domain, then this API will
provide for a generic poller.

This routine calls the [`edac_pci_alloc_ctl_info()`](#c-edac_pci_alloc_ctl_info) for
the generic device, with default values

**Return**

Pointer to struct `edac_pci_ctl_info` on success, `NULL` on
failure.

#### <a id="c-edac_pci_release_generic_ctl"></a>`edac_pci_release_generic_ctl()`

```c
void edac_pci_release_generic_ctl(struct edac_pci_ctl_info *pci)
```

**Parameters**

- `struct edac_pci_ctl_info *pci`: pointer to struct `edac_pci_ctl_info`

**Description**

The release function of a generic EDAC PCI polling device

#### <a id="c-edac_pci_create_sysfs"></a>`edac_pci_create_sysfs()`

```c
int edac_pci_create_sysfs(struct edac_pci_ctl_info *pci)
```

**Parameters**

- `struct edac_pci_ctl_info *pci`: pointer to struct `edac_pci_ctl_info`

**Description**

Create the controls/attributes for the specified EDAC PCI device

#### <a id="c-edac_pci_remove_sysfs"></a>`edac_pci_remove_sysfs()`

```c
void edac_pci_remove_sysfs(struct edac_pci_ctl_info *pci)
```

**Parameters**

- `struct edac_pci_ctl_info *pci`: pointer to struct `edac_pci_ctl_info`

**Description**

remove the controls and attributes for this EDAC PCI device


<a id="rst-edac-blocks"></a>

## EDAC Blocks

The EDAC subsystem also provides a generic mechanism to report errors on other parts of the hardware via `edac_device_alloc_ctl_info()` function.

The structures `edac_dev_sysfs_block_attribute`, `edac_device_block`, `edac_device_instance` and `edac_device_ctl_info` provide a generic or abstract 'edac_device' representation at sysfs.

This set of structures and the code that implements the APIs for the same, provide for registering EDAC type devices which are NOT standard memory or PCI, like:

- CPU caches (L1 and L2)

- DMA engines

- Core CPU switches

- Fabric switch units

- PCIe interface controllers

- other EDAC/ECC type devices that can be monitored for errors, etc.

It allows for a 2 level set of hierarchy.

For example, a cache could be composed of L1, L2 and L3 levels of cache. Each CPU core would have its own L1 cache, while sharing L2 and maybe L3 caches. On such case, those can be represented via the following sysfs nodes:



```text
/sys/devices/system/edac/..

pci/            <existing pci directory (if available)>
mc/             <existing memory device directory>
cpu/cpu0/..     <L1 and L2 block directory>
        /L1-cache/ce_count
                 /ue_count
        /L2-cache/ce_count
                 /ue_count
cpu/cpu1/..     <L1 and L2 block directory>
        /L1-cache/ce_count
                 /ue_count
        /L2-cache/ce_count
                 /ue_count
...

the L1 and L2 directories would be "edac_device_block's"
```


#### <a id="c-edac_device_add_device"></a>`edac_device_add_device()`

```c
int edac_device_add_device(struct edac_device_ctl_info *edac_dev)
```

Insert the 'edac_dev' structure into the edac_device global list and create sysfs entries associated with edac_device structure.

**Parameters**

- `struct edac_device_ctl_info *edac_dev`: pointer to edac_device structure to be added to the list
  'edac_device' structure.

**Return**

0 on Success, or an error code on failure

#### <a id="c-edac_device_del_device"></a>`edac_device_del_device()`

```c
struct edac_device_ctl_info * edac_device_del_device(struct device *dev)
```

Remove sysfs entries for specified edac_device structure and then remove edac_device structure from global list

**Parameters**

- `struct device *dev`: Pointer to struct [`device`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-struct-device) representing the edac device
  structure to remove.

**Return**

Pointer to removed edac_device structure,
or `NULL` if device not found.

#### <a id="c-edac_device_handle_ce_count"></a>`edac_device_handle_ce_count()`

```c
void edac_device_handle_ce_count(struct edac_device_ctl_info *edac_dev, unsigned int count, int inst_nr, int block_nr, const char *msg)
```

Log correctable errors.

**Parameters**

- `struct edac_device_ctl_info *edac_dev`: pointer to struct `edac_device_ctl_info`
- `unsigned int count`: Number of errors to log.
- `int inst_nr`: number of the instance where the CE error happened
- `int block_nr`: number of the block where the CE error happened
- `const char *msg`: message to be printed

#### <a id="c-edac_device_handle_ue_count"></a>`edac_device_handle_ue_count()`

```c
void edac_device_handle_ue_count(struct edac_device_ctl_info *edac_dev, unsigned int count, int inst_nr, int block_nr, const char *msg)
```

Log uncorrectable errors.

**Parameters**

- `struct edac_device_ctl_info *edac_dev`: pointer to struct `edac_device_ctl_info`
- `unsigned int count`: Number of errors to log.
- `int inst_nr`: number of the instance where the CE error happened
- `int block_nr`: number of the block where the CE error happened
- `const char *msg`: message to be printed

#### <a id="c-edac_device_handle_ce"></a>`edac_device_handle_ce()`

```c
void edac_device_handle_ce(struct edac_device_ctl_info *edac_dev, int inst_nr, int block_nr, const char *msg)
```

Log a single correctable error

**Parameters**

- `struct edac_device_ctl_info *edac_dev`: pointer to struct `edac_device_ctl_info`
- `int inst_nr`: number of the instance where the CE error happened
- `int block_nr`: number of the block where the CE error happened
- `const char *msg`: message to be printed

#### <a id="c-edac_device_handle_ue"></a>`edac_device_handle_ue()`

```c
void edac_device_handle_ue(struct edac_device_ctl_info *edac_dev, int inst_nr, int block_nr, const char *msg)
```

Log a single uncorrectable error

**Parameters**

- `struct edac_device_ctl_info *edac_dev`: pointer to struct `edac_device_ctl_info`
- `int inst_nr`: number of the instance where the UE error happened
- `int block_nr`: number of the block where the UE error happened
- `const char *msg`: message to be printed

#### <a id="c-edac_device_alloc_index"></a>`edac_device_alloc_index()`

```c
int edac_device_alloc_index(void)
```

Allocate a unique device index number

**Parameters**

- `void`: no arguments

**Return**

allocated index number


<a id="rst-heterogeneous-system-support"></a>

## Heterogeneous system support

An AMD heterogeneous system is built by connecting the data fabrics of both CPUs and GPUs via custom xGMI links. Thus, the data fabric on the GPU nodes can be accessed the same way as the data fabric on CPU nodes.

The MI200 accelerators are data center GPUs. They have 2 data fabrics, and each GPU data fabric contains four Unified Memory Controllers (UMC). Each UMC contains eight channels. Each UMC channel controls one 128-bit HBM2e (2GB) channel (equivalent to 8 X 2GB ranks).  This creates a total of 4096-bits of DRAM data bus.

While the UMC is interfacing a 16GB (8high X 2GB DRAM) HBM stack, each UMC channel is interfacing 2GB of DRAM (represented as rank).

Memory controllers on AMD GPU nodes can be represented in EDAC thusly:

> GPU DF / GPU Node -&gt; EDAC MC GPU UMC           -&gt; EDAC CSROW GPU UMC channel   -&gt; EDAC CHANNEL

For example: a heterogeneous system with 1 AMD CPU is connected to 4 MI200 (Aldebaran) GPUs using xGMI.

Some more heterogeneous hardware details:

- The CPU UMC (Unified Memory Controller) is mostly the same as the GPU UMC. They have chip selects (csrows) and channels. However, the layouts are different for performance, physical layout, or other reasons.

- CPU UMCs use 1 channel, In this case UMC = EDAC channel. This follows the marketing speak. CPU has X memory channels, etc.

- CPU UMCs use up to 4 chip selects, So UMC chip select = EDAC CSROW.

- GPU UMCs use 1 chip select, So UMC = EDAC CSROW.

- GPU UMCs use 8 channels, So UMC channel = EDAC channel.

The EDAC subsystem provides a mechanism to handle AMD heterogeneous systems by calling system specific ops for both CPUs and GPUs.

AMD GPU nodes are enumerated in sequential order based on the PCI hierarchy, and the first GPU node is assumed to have a Node ID value following those of the CPU nodes after latter are fully populated:



```text
$ ls /sys/devices/system/edac/mc/
        mc0   - CPU MC node 0
        mc1  |
        mc2  |- GPU card[0] => node 0(mc1), node 1(mc2)
        mc3  |
        mc4  |- GPU card[1] => node 0(mc3), node 1(mc4)
        mc5  |
        mc6  |- GPU card[2] => node 0(mc5), node 1(mc6)
        mc7  |
        mc8  |- GPU card[3] => node 0(mc7), node 1(mc8)
```

For example, a heterogeneous system with one AMD CPU is connected to four MI200 (Aldebaran) GPUs using xGMI. This topology can be represented via the following sysfs entries:



```text
/sys/devices/system/edac/mc/..

CPU                     # CPU node
├── mc 0

GPU Nodes are enumerated sequentially after CPU nodes have been populated
GPU card 1              # Each MI200 GPU has 2 nodes/mcs
├── mc 1                # GPU node 0 == mc1, Each MC node has 4 UMCs/CSROWs
│   ├── csrow 0         # UMC 0
│   │   ├── channel 0   # Each UMC has 8 channels
│   │   ├── channel 1   # size of each channel is 2 GB, so each UMC has 16 GB
│   │   ├── channel 2
│   │   ├── channel 3
│   │   ├── channel 4
│   │   ├── channel 5
│   │   ├── channel 6
│   │   ├── channel 7
│   ├── csrow 1         # UMC 1
│   │   ├── channel 0
│   │   ├── ..
│   │   ├── channel 7
│   ├── ..              ..
│   ├── csrow 3         # UMC 3
│   │   ├── channel 0
│   │   ├── ..
│   │   ├── channel 7
│   ├── rank 0
│   ├── ..              ..
│   ├── rank 31         # total 32 ranks/dimms from 4 UMCs
├
├── mc 2                # GPU node 1 == mc2
│   ├── ..              # each GPU has total 64 GB

GPU card 2
├── mc 3
│   ├── ..
├── mc 4
│   ├── ..

GPU card 3
├── mc 5
│   ├── ..
├── mc 6
│   ├── ..

GPU card 4
├── mc 7
│   ├── ..
├── mc 8
│   ├── ..
```

---

# Extcon Device Subsystem

_Peios Kernel / Hardware and drivers / Driver development / Clocks, signals and platform services_

> The Extcon (External Connector) subsystem provides a unified framework for managing external connectors in Linux systems. It allows drivers to report the state of external connectors and provides a standardized interface for userspace to…

<a id="rst-extcon-device-subsystem"></a>

<a id="rst-overview"></a>

## Overview

The Extcon (External Connector) subsystem provides a unified framework for managing external connectors in Linux systems. It allows drivers to report the state of external connectors and provides a standardized interface for userspace to query and monitor these states.

Extcon is particularly useful in modern devices with multiple connectivity options, such as smartphones, tablets, and laptops. It helps manage various types of connectors, including:

1. USB connectors (e.g., USB-C, micro-USB)

2. Charging ports (e.g., fast charging, wireless charging)

3. Audio jacks (e.g., 3.5mm headphone jack)

4. Video outputs (e.g., HDMI, DisplayPort)

5. Docking stations

Real-world examples:

1. Smartphone USB-C port: A single USB-C port on a smartphone can serve multiple functions. Extcon can manage the different states of this port, such as: - USB data connection - Charging (various types like fast charging, USB Power Delivery) - Audio output (USB-C headphones) - Video output (USB-C to HDMI adapter)

2. Laptop docking station: When a laptop is connected to a docking station, multiple connections are made simultaneously. Extcon can handle the state changes for: - Power delivery - External displays - USB hub connections - Ethernet connectivity

3. Wireless charging pad: Extcon can manage the state of a wireless charging connection, allowing the system to respond appropriately when a device is placed on or removed from the charging pad.

4. Smart TV HDMI ports: In a smart TV, Extcon can manage multiple HDMI ports, detecting when devices are connected or disconnected, and potentially identifying the type of device (e.g., gaming console, set-top box, Blu-ray player).

The Extcon framework simplifies the development of drivers for these complex scenarios by providing a standardized way to report and query connector states, handle mutually exclusive connections, and manage connector properties. This allows for more robust and flexible handling of external connections in modern devices.

<a id="rst-key-components"></a>

## Key Components

<a id="rst-extcon-dev"></a>

### extcon_dev

The core structure representing an Extcon device:



```text
struct extcon_dev {
    const char *name;
    const unsigned int *supported_cable;
    const u32 *mutually_exclusive;

    /* Internal data */
    struct device dev;
    unsigned int id;
    struct raw_notifier_head nh_all;
    struct raw_notifier_head *nh;
    struct list_head entry;
    int max_supported;
    spinlock_t lock;
    u32 state;

    /* Sysfs related */
    struct device_type extcon_dev_type;
    struct extcon_cable *cables;
    struct attribute_group attr_g_muex;
    struct attribute **attrs_muex;
    struct device_attribute *d_attrs_muex;
};
```

Key fields:

- `name`: Name of the Extcon device

- `supported_cable`: Array of supported cable types

- `mutually_exclusive`: Array defining mutually exclusive cable types This field is crucial for enforcing hardware constraints. It's an array of 32-bit unsigned integers, where each element represents a set of mutually exclusive cable types. The array should be terminated with a 0.

  For example:



  ```text
  static const u32 mutually_exclusive[] = {
      BIT(0) | BIT(1),  /* Cable 0 and 1 are mutually exclusive */
      BIT(2) | BIT(3) | BIT(4),  /* Cables 2, 3, and 4 are mutually exclusive */
      0  /* Terminator */
  };
  ```

  In this example, cables 0 and 1 cannot be connected simultaneously, and cables 2, 3, and 4 are also mutually exclusive. This is useful for scenarios like a single port that can either be USB or HDMI, but not both at the same time.

  The Extcon core uses this information to prevent invalid combinations of cable states, ensuring that the reported states are always consistent with the hardware capabilities.

- `state`: Current state of the device (bitmap of connected cables)

<a id="rst-extcon-cable"></a>

### extcon_cable

Represents an individual cable managed by an Extcon device:



```text
struct extcon_cable {
    struct extcon_dev *edev;
    int cable_index;
    struct attribute_group attr_g;
    struct device_attribute attr_name;
    struct device_attribute attr_state;
    struct attribute *attrs[3];
    union extcon_property_value usb_propval[EXTCON_PROP_USB_CNT];
    union extcon_property_value chg_propval[EXTCON_PROP_CHG_CNT];
    union extcon_property_value jack_propval[EXTCON_PROP_JACK_CNT];
    union extcon_property_value disp_propval[EXTCON_PROP_DISP_CNT];
    DECLARE_BITMAP(usb_bits, EXTCON_PROP_USB_CNT);
    DECLARE_BITMAP(chg_bits, EXTCON_PROP_CHG_CNT);
    DECLARE_BITMAP(jack_bits, EXTCON_PROP_JACK_CNT);
    DECLARE_BITMAP(disp_bits, EXTCON_PROP_DISP_CNT);
};
```

<a id="rst-core-functions"></a>

## Core Functions


#### <a id="c-extcon_get_state"></a>`extcon_get_state()`

```c
int extcon_get_state(struct extcon_dev *edev, const unsigned int id)
```

Get the state of an external connector.

**Parameters**

- `struct extcon_dev *edev`: the extcon device
- `const unsigned int id`: the unique id indicating an external connector

**Description**

Returns 0 if success or error number if fail.



#### <a id="c-extcon_set_state"></a>`extcon_set_state()`

```c
int extcon_set_state(struct extcon_dev *edev, unsigned int id, bool state)
```

Set the state of an external connector.

**Parameters**

- `struct extcon_dev *edev`: the extcon device
- `unsigned int id`: the unique id indicating an external connector
- `bool state`: the new state of an external connector.
  the default semantics is true: attached / false: detached.

**Description**

Note that this function set the state of an external connector without
a notification. To synchronize the state of an external connector,
have to use [`extcon_set_state_sync()`](#c-extcon_set_state_sync) and `extcon_sync()`.

Returns 0 if success or error number if fail.



#### <a id="c-extcon_set_state_sync"></a>`extcon_set_state_sync()`

```c
int extcon_set_state_sync(struct extcon_dev *edev, unsigned int id, bool state)
```

Set the state of an external connector with sync.

**Parameters**

- `struct extcon_dev *edev`: the extcon device
- `unsigned int id`: the unique id indicating an external connector
- `bool state`: the new state of external connector.
  the default semantics is true: attached / false: detached.

**Description**

Note that this function set the state of external connector
and synchronize the state by sending a notification.

Returns 0 if success or error number if fail.



#### <a id="c-extcon_get_property"></a>`extcon_get_property()`

```c
int extcon_get_property(struct extcon_dev *edev, unsigned int id, unsigned int prop, union extcon_property_value *prop_val)
```

Get the property value of an external connector.

**Parameters**

- `struct extcon_dev *edev`: the extcon device
- `unsigned int id`: the unique id indicating an external connector
- `unsigned int prop`: the property id indicating an extcon property
- `union extcon_property_value *prop_val`: the pointer which store the value of extcon property

**Description**

Note that when getting the property value of external connector,
the external connector should be attached. If detached state, function
return 0 without property value. Also, the each property should be
included in the list of supported properties according to extcon type.

Returns 0 if success or error number if fail.


<a id="rst-sysfs-interface"></a>

## Sysfs Interface

Extcon devices expose the following sysfs attributes:

- `name`: Name of the Extcon device

- `state`: Current state of all supported cables

- `cable.N/name`: Name of the Nth supported cable

- `cable.N/state`: State of the Nth supported cable

<a id="rst-usage-example"></a>

### Usage Example



```c
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/extcon.h>

struct my_extcon_data {
    struct extcon_dev *edev;
    struct device *dev;
};

static const unsigned int my_extcon_cable[] = {
    EXTCON_USB,
    EXTCON_USB_HOST,
    EXTCON_NONE,
};

static int my_extcon_probe(struct platform_device *pdev)
{
    struct my_extcon_data *data;
    int ret;

    data = devm_kzalloc(&pdev->dev, sizeof(*data), GFP_KERNEL);
    if (!data)
        return -ENOMEM;

    data->dev = &pdev->dev;

    /* Initialize extcon device */
    data->edev = devm_extcon_dev_allocate(data->dev, my_extcon_cable);
    if (IS_ERR(data->edev)) {
        dev_err(data->dev, "Failed to allocate extcon device\n");
        return PTR_ERR(data->edev);
    }

    /* Register extcon device */
    ret = devm_extcon_dev_register(data->dev, data->edev);
    if (ret < 0) {
        dev_err(data->dev, "Failed to register extcon device\n");
        return ret;
    }

    platform_set_drvdata(pdev, data);

    /* Example: Set initial state */
    extcon_set_state_sync(data->edev, EXTCON_USB, true);

    dev_info(data->dev, "My extcon driver probed successfully\n");
    return 0;
}

static int my_extcon_remove(struct platform_device *pdev)
{
    struct my_extcon_data *data = platform_get_drvdata(pdev);

    /* Example: Clear state before removal */
    extcon_set_state_sync(data->edev, EXTCON_USB, false);

    dev_info(data->dev, "My extcon driver removed\n");
    return 0;
}

static const struct of_device_id my_extcon_of_match[] = {
    { .compatible = "my,extcon-device", },
    { },
};
MODULE_DEVICE_TABLE(of, my_extcon_of_match);

static struct platform_driver my_extcon_driver = {
    .driver = {
        .name = "my-extcon-driver",
        .of_match_table = my_extcon_of_match,
    },
    .probe = my_extcon_probe,
    .remove = my_extcon_remove,
};

module_platform_driver(my_extcon_driver);
```

<a id="rst-this-example-demonstrates"></a>

### This example demonstrates:

- Defining supported cable types (USB and USB Host in this case).

- Allocating and registering an extcon device.

- Setting an initial state for a cable (USB connected in this example).

- Clearing the state when the driver is removed.

---

# Generic Counter Interface

_Peios Kernel / Hardware and drivers / Driver development / Clocks, signals and platform services_

> Counter devices are prevalent among a diverse spectrum of industries. The ubiquitous presence of these devices necessitates a common interface and standard of interaction and exposure. This driver API attempts to resolve the issue of…

<a id="rst-generic-counter-interface"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-introduction"></a>

## Introduction

Counter devices are prevalent among a diverse spectrum of industries. The ubiquitous presence of these devices necessitates a common interface and standard of interaction and exposure. This driver API attempts to resolve the issue of duplicate code found among existing counter device drivers by introducing a generic counter interface for consumption. The Generic Counter interface enables drivers to support and expose a common set of components and functionality present in counter devices.

<a id="rst-theory"></a>

## Theory

Counter devices can vary greatly in design, but regardless of whether some devices are quadrature encoder counters or tally counters, all counter devices consist of a core set of components. This core set of components, shared by all counter devices, is what forms the essence of the Generic Counter interface.

There are three core components to a counter:

- Signal: Stream of data to be evaluated by the counter.

- Synapse: Association of a Signal, and evaluation trigger, with a Count.

- Count: Accumulation of the effects of connected Synapses.

<a id="rst-signal"></a>

### SIGNAL

A Signal represents a stream of data. This is the input data that is evaluated by the counter to determine the count data; e.g. a quadrature signal output line of a rotary encoder. Not all counter devices provide user access to the Signal data, so exposure is optional for drivers.

When the Signal data is available for user access, the Generic Counter interface provides the following available signal values:

- SIGNAL_LOW: Signal line is in a low state.

- SIGNAL_HIGH: Signal line is in a high state.

A Signal may be associated with one or more Counts.

<a id="rst-synapse"></a>

### SYNAPSE

A Synapse represents the association of a Signal with a Count. Signal data affects respective Count data, and the Synapse represents this relationship.

The Synapse action mode specifies the Signal data condition that triggers the respective Count's count function evaluation to update the count data. The Generic Counter interface provides the following available action modes:

- None: Signal does not trigger the count function. In Pulse-Direction count function mode, this Signal is evaluated as Direction.

- Rising Edge: Low state transitions to high state.

- Falling Edge: High state transitions to low state.

- Both Edges: Any state transition.

A counter is defined as a set of input signals associated with count data that are generated by the evaluation of the state of the associated input signals as defined by the respective count functions. Within the context of the Generic Counter interface, a counter consists of Counts each associated with a set of Signals, whose respective Synapse instances represent the count function update conditions for the associated Counts.

A Synapse associates one Signal with one Count.

<a id="rst-count"></a>

### COUNT

A Count represents the accumulation of the effects of connected Synapses; i.e. the count data for a set of Signals. The Generic Counter interface represents the count data as a natural number.

A Count has a count function mode which represents the update behavior for the count data. The Generic Counter interface provides the following available count function modes:

- Increase: Accumulated count is incremented.

- Decrease: Accumulated count is decremented.

- Pulse-Direction: Rising edges on signal A updates the respective count. The input level of signal B determines direction.

- Quadrature: A pair of quadrature encoding signals are evaluated to determine position and direction. The following Quadrature modes are available:

  - x1 A: If direction is forward, rising edges on quadrature pair signal A updates the respective count; if the direction is backward, falling edges on quadrature pair signal A updates the respective count. Quadrature encoding determines the direction.

  - x1 B: If direction is forward, rising edges on quadrature pair signal B updates the respective count; if the direction is backward, falling edges on quadrature pair signal B updates the respective count. Quadrature encoding determines the direction.

  - x2 A: Any state transition on quadrature pair signal A updates the respective count. Quadrature encoding determines the direction.

  - x2 B: Any state transition on quadrature pair signal B updates the respective count. Quadrature encoding determines the direction.

  - x4: Any state transition on either quadrature pair signals updates the respective count. Quadrature encoding determines the direction.

A Count has a set of one or more associated Synapses.

<a id="rst-paradigm"></a>

## Paradigm

The most basic counter device may be expressed as a single Count associated with a single Signal via a single Synapse. Take for example a counter device which simply accumulates a count of rising edges on a source input line:



```text
        Count                Synapse        Signal
        -----                -------        ------
+---------------------+
| Data: Count         |    Rising Edge     ________
| Function: Increase  |  <-------------   / Source \
|                     |                  ____________
+---------------------+
```

In this example, the Signal is a source input line with a pulsing voltage, while the Count is a persistent count value which is repeatedly incremented. The Signal is associated with the respective Count via a Synapse. The increase function is triggered by the Signal data condition specified by the Synapse -- in this case a rising edge condition on the voltage input line. In summary, the counter device existence and behavior is aptly represented by respective Count, Signal, and Synapse components: a rising edge condition triggers an increase function on an accumulating count datum.

A counter device is not limited to a single Signal; in fact, in theory many Signals may be associated with even a single Count. For example, a quadrature encoder counter device can keep track of position based on the states of two input lines:



```text
           Count                 Synapse     Signal
           -----                 -------     ------
+-------------------------+
| Data: Position          |    Both Edges     ___
| Function: Quadrature x4 |  <------------   / A \
|                         |                 _______
|                         |
|                         |    Both Edges     ___
|                         |  <------------   / B \
|                         |                 _______
+-------------------------+
```

In this example, two Signals (quadrature encoder lines A and B) are associated with a single Count: a rising or falling edge on either A or B triggers the "Quadrature x4" function which determines the direction of movement and updates the respective position data. The "Quadrature x4" function is likely implemented in the hardware of the quadrature encoder counter device; the Count, Signals, and Synapses simply represent this hardware behavior and functionality.

Signals associated with the same Count can have differing Synapse action mode conditions. For example, a quadrature encoder counter device operating in a non-quadrature Pulse-Direction mode could have one input line dedicated for movement and a second input line dedicated for direction:



```text
           Count                   Synapse      Signal
           -----                   -------      ------
+---------------------------+
| Data: Position            |    Rising Edge     ___
| Function: Pulse-Direction |  <-------------   / A \ (Movement)
|                           |                  _______
|                           |
|                           |       None         ___
|                           |  <-------------   / B \ (Direction)
|                           |                  _______
+---------------------------+
```

Only Signal A triggers the "Pulse-Direction" update function, but the instantaneous state of Signal B is still required in order to know the direction so that the position data may be properly updated. Ultimately, both Signals are associated with the same Count via two respective Synapses, but only one Synapse has an active action mode condition which triggers the respective count function while the other is left with a "None" condition action mode to indicate its respective Signal's availability for state evaluation despite its non-triggering mode.

Keep in mind that the Signal, Synapse, and Count are abstract representations which do not need to be closely married to their respective physical sources. This allows the user of a counter to divorce themselves from the nuances of physical components (such as whether an input line is differential or single-ended) and instead focus on the core idea of what the data and process represent (e.g. position as interpreted from quadrature encoding data).

<a id="rst-driver-api"></a>

## Driver API

Driver authors may utilize the Generic Counter interface in their code by including the include/linux/counter.h header file. This header file provides several core data structures, function prototypes, and macros for defining a counter device.


#### <a id="c-struct-counter_comp"></a>`struct counter_comp`

Counter component node

**Definition**

```c
struct counter_comp {
    enum counter_comp_type type;
    const char *name;
    void *priv;
    union {
        int (*action_read)(struct counter_device *counter, struct counter_count *count, struct counter_synapse *synapse, enum counter_synapse_action *action);
        int (*device_u8_read)(struct counter_device *counter, u8 *val);
        int (*count_u8_read)(struct counter_device *counter, struct counter_count *count, u8 *val);
        int (*signal_u8_read)(struct counter_device *counter, struct counter_signal *signal, u8 *val);
        int (*device_u32_read)(struct counter_device *counter, u32 *val);
        int (*count_u32_read)(struct counter_device *counter, struct counter_count *count, u32 *val);
        int (*signal_u32_read)(struct counter_device *counter, struct counter_signal *signal, u32 *val);
        int (*device_u64_read)(struct counter_device *counter, u64 *val);
        int (*count_u64_read)(struct counter_device *counter, struct counter_count *count, u64 *val);
        int (*signal_u64_read)(struct counter_device *counter, struct counter_signal *signal, u64 *val);
        int (*signal_array_u32_read)(struct counter_device *counter, struct counter_signal *signal, size_t idx, u32 *val);
        int (*device_array_u64_read)(struct counter_device *counter, size_t idx, u64 *val);
        int (*count_array_u64_read)(struct counter_device *counter, struct counter_count *count, size_t idx, u64 *val);
        int (*signal_array_u64_read)(struct counter_device *counter, struct counter_signal *signal, size_t idx, u64 *val);
    };
    union {
        int (*action_write)(struct counter_device *counter, struct counter_count *count, struct counter_synapse *synapse, enum counter_synapse_action action);
        int (*device_u8_write)(struct counter_device *counter, u8 val);
        int (*count_u8_write)(struct counter_device *counter, struct counter_count *count, u8 val);
        int (*signal_u8_write)(struct counter_device *counter, struct counter_signal *signal, u8 val);
        int (*device_u32_write)(struct counter_device *counter, u32 val);
        int (*count_u32_write)(struct counter_device *counter, struct counter_count *count, u32 val);
        int (*signal_u32_write)(struct counter_device *counter, struct counter_signal *signal, u32 val);
        int (*device_u64_write)(struct counter_device *counter, u64 val);
        int (*count_u64_write)(struct counter_device *counter, struct counter_count *count, u64 val);
        int (*signal_u64_write)(struct counter_device *counter, struct counter_signal *signal, u64 val);
        int (*signal_array_u32_write)(struct counter_device *counter, struct counter_signal *signal, size_t idx, u32 val);
        int (*device_array_u64_write)(struct counter_device *counter, size_t idx, u64 val);
        int (*count_array_u64_write)(struct counter_device *counter, struct counter_count *count, size_t idx, u64 val);
        int (*signal_array_u64_write)(struct counter_device *counter, struct counter_signal *signal, size_t idx, u64 val);
    };
};
```

**Members**

- `type`: Counter component data type
- `name`: device-specific component name
- `priv`: component-relevant data
- `{unnamed_union}`: anonymous
- `action_read`: Synapse action mode read callback. The read value of the
  respective Synapse action mode should be passed back via
  the action parameter.
- `device_u8_read`: Device u8 component read callback. The read value of the
  respective Device u8 component should be passed back via
  the val parameter.
- `count_u8_read`: Count u8 component read callback. The read value of the
  respective Count u8 component should be passed back via
  the val parameter.
- `signal_u8_read`: Signal u8 component read callback. The read value of the
  respective Signal u8 component should be passed back via
  the val parameter.
- `device_u32_read`: Device u32 component read callback. The read value of
  the respective Device u32 component should be passed
  back via the val parameter.
- `count_u32_read`: Count u32 component read callback. The read value of the
  respective Count u32 component should be passed back via
  the val parameter.
- `signal_u32_read`: Signal u32 component read callback. The read value of
  the respective Signal u32 component should be passed
  back via the val parameter.
- `device_u64_read`: Device u64 component read callback. The read value of
  the respective Device u64 component should be passed
  back via the val parameter.
- `count_u64_read`: Count u64 component read callback. The read value of the
  respective Count u64 component should be passed back via
  the val parameter.
- `signal_u64_read`: Signal u64 component read callback. The read value of
  the respective Signal u64 component should be passed
  back via the val parameter.
- `signal_array_u32_read`: Signal u32 array component read callback. The
  index of the respective Count u32 array
  component element is passed via the idx
  parameter. The read value of the respective
  Count u32 array component element should be
  passed back via the val parameter.
- `device_array_u64_read`: Device u64 array component read callback. The
  index of the respective Device u64 array
  component element is passed via the idx
  parameter. The read value of the respective
  Device u64 array component element should be
  passed back via the val parameter.
- `count_array_u64_read`: Count u64 array component read callback. The
  index of the respective Count u64 array
  component element is passed via the idx
  parameter. The read value of the respective
  Count u64 array component element should be
  passed back via the val parameter.
- `signal_array_u64_read`: Signal u64 array component read callback. The
  index of the respective Count u64 array
  component element is passed via the idx
  parameter. The read value of the respective
  Count u64 array component element should be
  passed back via the val parameter.
- `{unnamed_union}`: anonymous
- `action_write`: Synapse action mode write callback. The write value of
  the respective Synapse action mode is passed via the
  action parameter.
- `device_u8_write`: Device u8 component write callback. The write value of
  the respective Device u8 component is passed via the val
  parameter.
- `count_u8_write`: Count u8 component write callback. The write value of
  the respective Count u8 component is passed via the val
  parameter.
- `signal_u8_write`: Signal u8 component write callback. The write value of
  the respective Signal u8 component is passed via the val
  parameter.
- `device_u32_write`: Device u32 component write callback. The write value of
  the respective Device u32 component is passed via the
  val parameter.
- `count_u32_write`: Count u32 component write callback. The write value of
  the respective Count u32 component is passed via the val
  parameter.
- `signal_u32_write`: Signal u32 component write callback. The write value of
  the respective Signal u32 component is passed via the
  val parameter.
- `device_u64_write`: Device u64 component write callback. The write value of
  the respective Device u64 component is passed via the
  val parameter.
- `count_u64_write`: Count u64 component write callback. The write value of
  the respective Count u64 component is passed via the val
  parameter.
- `signal_u64_write`: Signal u64 component write callback. The write value of
  the respective Signal u64 component is passed via the
  val parameter.
- `signal_array_u32_write`: Signal u32 array component write callback. The
  index of the respective Signal u32 array
  component element is passed via the idx
  parameter. The write value of the respective
  Signal u32 array component element is passed via
  the val parameter.
- `device_array_u64_write`: Device u64 array component write callback. The
  index of the respective Device u64 array
  component element is passed via the idx
  parameter. The write value of the respective
  Device u64 array component element is passed via
  the val parameter.
- `count_array_u64_write`: Count u64 array component write callback. The
  index of the respective Count u64 array
  component element is passed via the idx
  parameter. The write value of the respective
  Count u64 array component element is passed via
  the val parameter.
- `signal_array_u64_write`: Signal u64 array component write callback. The
  index of the respective Signal u64 array
  component element is passed via the idx
  parameter. The write value of the respective
  Signal u64 array component element is passed via
  the val parameter.

#### <a id="c-struct-counter_signal"></a>`struct counter_signal`

Counter Signal node

**Definition**

```c
struct counter_signal {
    int id;
    const char *name;
    struct counter_comp *ext;
    size_t num_ext;
};
```

**Members**

- `id`: unique ID used to identify the Signal
- `name`: device-specific Signal name
- `ext`: optional array of Signal extensions
- `num_ext`: number of Signal extensions specified in **ext**

#### <a id="c-struct-counter_synapse"></a>`struct counter_synapse`

Counter Synapse node

**Definition**

```c
struct counter_synapse {
    const enum counter_synapse_action *actions_list;
    size_t num_actions;
    struct counter_signal *signal;
};
```

**Members**

- `actions_list`: array of available action modes
- `num_actions`: number of action modes specified in **actions_list**
- `signal`: pointer to the associated Signal

#### <a id="c-struct-counter_count"></a>`struct counter_count`

Counter Count node

**Definition**

```c
struct counter_count {
    int id;
    const char *name;
    const enum counter_function *functions_list;
    size_t num_functions;
    struct counter_synapse *synapses;
    size_t num_synapses;
    struct counter_comp *ext;
    size_t num_ext;
};
```

**Members**

- `id`: unique ID used to identify the Count
- `name`: device-specific Count name
- `functions_list`: array of available function modes
- `num_functions`: number of function modes specified in **functions_list**
- `synapses`: array of Synapses for initialization
- `num_synapses`: number of Synapses specified in **synapses**
- `ext`: optional array of Count extensions
- `num_ext`: number of Count extensions specified in **ext**

#### <a id="c-struct-counter_event_node"></a>`struct counter_event_node`

Counter Event node

**Definition**

```c
struct counter_event_node {
    struct list_head l;
    u8 event;
    u8 channel;
    struct list_head comp_list;
};
```

**Members**

- `l`: list of current watching Counter events
- `event`: event that triggers
- `channel`: event channel
- `comp_list`: list of components to watch when event triggers

#### <a id="c-struct-counter_ops"></a>`struct counter_ops`

Callbacks from driver

**Definition**

```c
struct counter_ops {
    int (*signal_read)(struct counter_device *counter, struct counter_signal *signal, enum counter_signal_level *level);
    int (*count_read)(struct counter_device *counter, struct counter_count *count, u64 *value);
    int (*count_write)(struct counter_device *counter, struct counter_count *count, u64 value);
    int (*function_read)(struct counter_device *counter, struct counter_count *count, enum counter_function *function);
    int (*function_write)(struct counter_device *counter, struct counter_count *count, enum counter_function function);
    int (*action_read)(struct counter_device *counter, struct counter_count *count, struct counter_synapse *synapse, enum counter_synapse_action *action);
    int (*action_write)(struct counter_device *counter, struct counter_count *count, struct counter_synapse *synapse, enum counter_synapse_action action);
    int (*events_configure)(struct counter_device *counter);
    int (*watch_validate)(struct counter_device *counter, const struct counter_watch *watch);
};
```

**Members**

- `signal_read`: optional read callback for Signals. The read level of
  the respective Signal should be passed back via the
  level parameter.
- `count_read`: read callback for Counts. The read value of the
  respective Count should be passed back via the value
  parameter.
- `count_write`: optional write callback for Counts. The write value for
  the respective Count is passed in via the value
  parameter.
- `function_read`: read callback the Count function modes. The read
  function mode of the respective Count should be passed
  back via the function parameter.
- `function_write`: optional write callback for Count function modes. The
  function mode to write for the respective Count is
  passed in via the function parameter.
- `action_read`: optional read callback the Synapse action modes. The
  read action mode of the respective Synapse should be
  passed back via the action parameter.
- `action_write`: optional write callback for Synapse action modes. The
  action mode to write for the respective Synapse is
  passed in via the action parameter.
- `events_configure`: optional write callback to configure events. The list of
  struct counter_event_node may be accessed via the
  events_list member of the counter parameter.
- `watch_validate`: optional callback to validate a watch. The Counter
  component watch configuration is passed in via the watch
  parameter. A return value of 0 indicates a valid Counter
  component watch configuration.

#### <a id="c-struct-counter_device"></a>`struct counter_device`

Counter data structure

**Definition**

```c
struct counter_device {
    const char *name;
    struct device *parent;
    const struct counter_ops *ops;
    struct counter_signal *signals;
    size_t num_signals;
    struct counter_count *counts;
    size_t num_counts;
    struct counter_comp *ext;
    size_t num_ext;
    struct device dev;
    struct cdev chrdev;
    struct list_head events_list;
    spinlock_t events_list_lock;
    struct list_head next_events_list;
    struct mutex n_events_list_lock;
    struct counter_event *events;
    wait_queue_head_t events_wait;
    spinlock_t events_in_lock;
    struct mutex events_out_lock;
    struct mutex ops_exist_lock;
};
```

**Members**

- `name`: name of the device
- `parent`: optional parent device providing the counters
- `ops`: callbacks from driver
- `signals`: array of Signals
- `num_signals`: number of Signals specified in **signals**
- `counts`: array of Counts
- `num_counts`: number of Counts specified in **counts**
- `ext`: optional array of Counter device extensions
- `num_ext`: number of Counter device extensions specified in **ext**
- `dev`: internal device structure
- `chrdev`: internal character device structure
- `events_list`: list of current watching Counter events
- `events_list_lock`: lock to protect Counter events list operations
- `next_events_list`: list of next watching Counter events
- `n_events_list_lock`: lock to protect Counter next events list operations
- `events`: queue of detected Counter events
- `events_wait`: wait queue to allow blocking reads of Counter events
- `events_in_lock`: lock to protect Counter events queue in operations
- `events_out_lock`: lock to protect Counter events queue out operations
- `ops_exist_lock`: lock to prevent use during removal



#### <a id="c-counter_priv"></a>`counter_priv()`

```c
void * counter_priv(const struct counter_device *const counter)
```

access counter device private data

**Parameters**

- `const struct counter_device *const counter`: counter device

**Description**

Get the counter device private data

#### <a id="c-counter_alloc"></a>`counter_alloc()`

```c
struct counter_device * counter_alloc(size_t sizeof_priv)
```

allocate a counter_device

**Parameters**

- `size_t sizeof_priv`: size of the driver private data

**Description**

This is part one of counter registration. The structure is allocated
dynamically to ensure the right lifetime for the embedded struct device.

If this succeeds, call `counter_put()` to get rid of the counter_device again.

#### <a id="c-counter_add"></a>`counter_add()`

```c
int counter_add(struct counter_device *counter)
```

complete registration of a counter

**Parameters**

- `struct counter_device *counter`: the counter to add

**Description**

This is part two of counter registration.

If this succeeds, call [`counter_unregister()`](#c-counter_unregister) to get rid of the counter_device again.

#### <a id="c-counter_unregister"></a>`counter_unregister()`

```c
void counter_unregister(struct counter_device *const counter)
```

unregister Counter from the system

**Parameters**

- `struct counter_device *const counter`: pointer to Counter to unregister

**Description**

The Counter is unregistered from the system.

#### <a id="c-devm_counter_alloc"></a>`devm_counter_alloc()`

```c
struct counter_device * devm_counter_alloc(struct device *dev, size_t sizeof_priv)
```

allocate a counter_device

**Parameters**

- `struct device *dev`: the device to register the release callback for
- `size_t sizeof_priv`: size of the driver private data

**Description**

This is the device managed version of [`counter_add()`](#c-counter_add). It registers a cleanup
callback to care for calling `counter_put()`.

#### <a id="c-devm_counter_add"></a>`devm_counter_add()`

```c
int devm_counter_add(struct device *dev, struct counter_device *const counter)
```

complete registration of a counter

**Parameters**

- `struct device *dev`: the device to register the release callback for
- `struct counter_device *const counter`: the counter to add

**Description**

This is the device managed version of [`counter_add()`](#c-counter_add). It registers a cleanup
callback to care for calling [`counter_unregister()`](#c-counter_unregister).



#### <a id="c-counter_push_event"></a>`counter_push_event()`

```c
void counter_push_event(struct counter_device *const counter, const u8 event, const u8 channel)
```

queue event for userspace reading

**Parameters**

- `struct counter_device *const counter`: pointer to Counter structure
- `const u8 event`: triggered event
- `const u8 channel`: event channel

**Note**

If no one is watching for the respective event, it is silently
discarded.


<a id="rst-driver-implementation"></a>

## Driver Implementation

To support a counter device, a driver must first allocate the available Counter Signals via counter_signal structures. These Signals should be stored as an array and set to the signals array member of an allocated counter_device structure before the Counter is registered to the system.

Counter Counts may be allocated via counter_count structures, and respective Counter Signal associations (Synapses) made via counter_synapse structures. Associated counter_synapse structures are stored as an array and set to the synapses array member of the respective counter_count structure. These counter_count structures are set to the counts array member of an allocated counter_device structure before the Counter is registered to the system.

Driver callbacks must be provided to the counter_device structure in order to communicate with the device: to read and write various Signals and Counts, and to set and get the "action mode" and "function mode" for various Synapses and Counts respectively.

A counter_device structure is allocated using counter_alloc() and then registered to the system by passing it to the counter_add() function, and unregistered by passing it to the counter_unregister function. There are device managed variants of these functions: devm_counter_alloc() and devm_counter_add().

The struct counter_comp structure is used to define counter extensions for Signals, Synapses, and Counts.

The "type" member specifies the type of high-level data (e.g. BOOL, COUNT_DIRECTION, etc.) handled by this extension. The "`*_read`" and "`*_write`" members can then be set by the counter device driver with callbacks to handle that data using native C data types (i.e. u8, u64, etc.).

Convenience macros such as `COUNTER_COMP_COUNT_U64` are provided for use by driver authors. In particular, driver authors are expected to use the provided macros for standard Counter subsystem attributes in order to maintain a consistent interface for userspace. For example, a counter device driver may define several standard attributes like so:



```text
struct counter_comp count_ext[] = {
        COUNTER_COMP_DIRECTION(count_direction_read),
        COUNTER_COMP_ENABLE(count_enable_read, count_enable_write),
        COUNTER_COMP_CEILING(count_ceiling_read, count_ceiling_write),
};
```

This makes it simple to see, add, and modify the attributes that are supported by this driver ("direction", "enable", and "ceiling") and to maintain this code without getting lost in a web of struct braces.

Callbacks must match the function type expected for the respective component or extension. These function types are defined in the struct counter_comp structure as the "`*_read`" and "`*_write`" union members.

The corresponding callback prototypes for the extensions mentioned in the previous example above would be:



```text
int count_direction_read(struct counter_device *counter,
                         struct counter_count *count,
                         enum counter_count_direction *direction);
int count_enable_read(struct counter_device *counter,
                      struct counter_count *count, u8 *enable);
int count_enable_write(struct counter_device *counter,
                       struct counter_count *count, u8 enable);
int count_ceiling_read(struct counter_device *counter,
                       struct counter_count *count, u64 *ceiling);
int count_ceiling_write(struct counter_device *counter,
                        struct counter_count *count, u64 ceiling);
```

Determining the type of extension to create is a matter of scope.

- Signal extensions are attributes that expose information/control specific to a Signal. These types of attributes will exist under a Signal's directory in sysfs.

  For example, if you have an invert feature for a Signal, you can have a Signal extension called "invert" that toggles that feature: /sys/bus/counter/devices/counterX/signalY/invert

- Count extensions are attributes that expose information/control specific to a Count. These type of attributes will exist under a Count's directory in sysfs.

  For example, if you want to pause/unpause a Count from updating, you can have a Count extension called "enable" that toggles such: /sys/bus/counter/devices/counterX/countY/enable

- Device extensions are attributes that expose information/control non-specific to a particular Count or Signal. This is where you would put your global features or other miscellaneous functionality.

  For example, if your device has an overtemp sensor, you can report the chip overheated via a device extension called "error_overtemp": /sys/bus/counter/devices/counterX/error_overtemp

<a id="rst-subsystem-architecture"></a>

## Subsystem Architecture

Counter drivers pass and take data natively (i.e. `u8`, `u64`, etc.) and the shared counter module handles the translation between the sysfs interface. This guarantees a standard userspace interface for all counter drivers, and enables a Generic Counter chrdev interface via a generalized device driver ABI.

A high-level view of how a count value is passed down from a counter driver is exemplified by the following. The driver callbacks are first registered to the Counter core component for use by the Counter userspace interface components:



```text
Driver callbacks registration:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
                +----------------------------+
                | Counter device driver      |
                +----------------------------+
                | Processes data from device |
                +----------------------------+
                        |
                 -------------------
                / driver callbacks /
                -------------------
                        |
                        V
                +----------------------+
                | Counter core         |
                +----------------------+
                | Routes device driver |
                | callbacks to the     |
                | userspace interfaces |
                +----------------------+
                        |
                 -------------------
                / driver callbacks /
                -------------------
                        |
        +---------------+---------------+
        |                               |
        V                               V
+--------------------+          +---------------------+
| Counter sysfs      |          | Counter chrdev      |
+--------------------+          +---------------------+
| Translates to the  |          | Translates to the   |
| standard Counter   |          | standard Counter    |
| sysfs output       |          | character device    |
+--------------------+          +---------------------+
```

Thereafter, data can be transferred directly between the Counter device driver and Counter userspace interface:



```text
Count data request:
~~~~~~~~~~~~~~~~~~~
                 ----------------------
                / Counter device       \
                +----------------------+
                | Count register: 0x28 |
                +----------------------+
                        |
                 -----------------
                / raw count data /
                -----------------
                        |
                        V
                +----------------------------+
                | Counter device driver      |
                +----------------------------+
                | Processes data from device |
                |----------------------------|
                | Type: u64                  |
                | Value: 42                  |
                +----------------------------+
                        |
                 ----------
                / u64     /
                ----------
                        |
        +---------------+---------------+
        |                               |
        V                               V
+--------------------+          +---------------------+
| Counter sysfs      |          | Counter chrdev      |
+--------------------+          +---------------------+
| Translates to the  |          | Translates to the   |
| standard Counter   |          | standard Counter    |
| sysfs output       |          | character device    |
|--------------------|          |---------------------|
| Type: const char * |          | Type: u64           |
| Value: "42"        |          | Value: 42           |
+--------------------+          +---------------------+
        |                               |
 ---------------                 -----------------------
/ const char * /                / struct counter_event /
---------------                 -----------------------
        |                               |
        |                               V
        |                       +-----------+
        |                       | read      |
        |                       +-----------+
        |                       \ Count: 42 /
        |                        -----------
        |
        V
+--------------------------------------------------+
| `/sys/bus/counter/devices/counterX/countY/count` |
+--------------------------------------------------+
\ Count: "42"                                      /
 --------------------------------------------------
```

There are four primary components involved:

<a id="rst-counter-device-driver"></a>

### Counter device driver

Communicates with the hardware device to read/write data; e.g. counter drivers for quadrature encoders, timers, etc.

<a id="rst-counter-core"></a>

### Counter core

Registers the counter device driver to the system so that the respective callbacks are called during userspace interaction.

<a id="rst-counter-sysfs"></a>

### Counter sysfs

Translates counter data to the standard Counter sysfs interface format and vice versa.

Please refer to the Documentation/ABI/testing/sysfs-bus-counter file for a detailed breakdown of the available Generic Counter interface sysfs attributes.

<a id="rst-counter-chrdev"></a>

### Counter chrdev

Translates Counter events to the standard Counter character device; data is transferred via standard character device read calls, while Counter events are configured via ioctl calls.

<a id="rst-sysfs-interface"></a>

## Sysfs Interface

Several sysfs attributes are generated by the Generic Counter interface, and reside under the `/sys/bus/counter/devices/counterX` directory, where `X` is to the respective counter device id. Please see Documentation/ABI/testing/sysfs-bus-counter for detailed information on each Generic Counter interface sysfs attribute.

Through these sysfs attributes, programs and scripts may interact with the Generic Counter paradigm Counts, Signals, and Synapses of respective counter devices.

<a id="rst-counter-character-device"></a>

## Counter Character Device

Counter character device nodes are created under the `/dev` directory as `counterX`, where `X` is the respective counter device id. Defines for the standard Counter data types are exposed via the userspace `include/uapi/linux/counter.h` file.

<a id="rst-counter-events"></a>

### Counter events

Counter device drivers can support Counter events by utilizing the `counter_push_event` function:



```text
void counter_push_event(struct counter_device *const counter, const u8 event,
                        const u8 channel);
```

The event id is specified by the `event` parameter; the event channel id is specified by the `channel` parameter. When this function is called, the Counter data associated with the respective event is gathered, and a `struct counter_event` is generated for each datum and pushed to userspace.

Counter events can be configured by users to report various Counter data of interest. This can be conceptualized as a list of Counter component read calls to perform. For example:

>
> <table>
> <thead>
> <tr>
> <th>
>
>
> COUNTER_EVENT_OVERFLOW
>
> </th>
> <th>
>
>
> COUNTER_EVENT_INDEX
>
> </th>
> </tr>
> </thead>
> <tbody>
> <tr>
> <td>
>
>
> Channel 0
>
> </td>
> <td>
>
>
> Channel 0
>
> </td>
> </tr>
> <tr>
> <td rowspan="3">
>
>
> - Count 0
>
> - Count 1
>
> - Signal 3
>
> - Count 4 Extension 2
>
> - Signal 5 Extension 0
>
> </td>
> <td>
>
>
> - Signal 0
>
> - Signal 0 Extension 0
>
> - Extension 4
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> Channel 1
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> - Signal 4
>
> - Signal 4 Extension 0
>
> - Count 7
>
> </td>
> </tr>
> </tbody>
> </table>

When `counter_push_event(counter, COUNTER_EVENT_INDEX, 1)` is called for example, it will go down the list for the `COUNTER_EVENT_INDEX` event channel 1 and execute the read callbacks for Signal 4, Signal 4 Extension 0, and Count 7 -- the data returned for each is pushed to a kfifo as a `struct counter_event`, which userspace can retrieve via a standard read operation on the respective character device node.

<a id="rst-userspace"></a>

### Userspace

Userspace applications can configure Counter events via ioctl operations on the Counter character device node. There following ioctl codes are supported and provided by the `linux/counter.h` userspace header file:

- `COUNTER_ADD_WATCH_IOCTL`

- `COUNTER_ENABLE_EVENTS_IOCTL`

- `COUNTER_DISABLE_EVENTS_IOCTL`

To configure events to gather Counter data, users first populate a `struct counter_watch` with the relevant event id, event channel id, and the information for the desired Counter component from which to read, and then pass it via the `COUNTER_ADD_WATCH_IOCTL` ioctl command.

Note that an event can be watched without gathering Counter data by setting the `component.type` member equal to `COUNTER_COMPONENT_NONE`. With this configuration the Counter character device will simply populate the event timestamps for those respective `struct counter_event` elements and ignore the component value.

The `COUNTER_ADD_WATCH_IOCTL` command will buffer these Counter watches. When ready, the `COUNTER_ENABLE_EVENTS_IOCTL` ioctl command may be used to activate these Counter watches.

Userspace applications can then execute a `read` operation (optionally calling `poll` first) on the Counter character device node to retrieve `struct counter_event` elements with the desired data.

---

# Recoverable Hardware Error Tracking in vmcoreinfo

_Peios Kernel / Hardware and drivers / Driver development / Clocks, signals and platform services_

> This feature provides a generic infrastructure within the Linux kernel to track and log recoverable hardware errors. These are hardware recoverable errors visible that might not cause immediate panics but may influence health, mainly…

<a id="rst-recoverable-hardware-error-tracking-in-vmcoreinfo"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-overview"></a>

## Overview

This feature provides a generic infrastructure within the Linux kernel to track and log recoverable hardware errors. These are hardware recoverable errors visible that might not cause immediate panics but may influence health, mainly because new code path will be executed in the kernel.

By recording counts and timestamps of recoverable errors into the vmcoreinfo crash dump notes, this infrastructure aids post-mortem crash analysis tools in correlating hardware events with kernel failures. This enables faster triage and better understanding of root causes, especially in large-scale cloud environments where hardware issues are common.

<a id="rst-benefits"></a>

## Benefits

- Facilitates correlation of hardware recoverable errors with kernel panics or unusual code paths that lead to system crashes.

- Provides operators and cloud providers quick insights, improving reliability and reducing troubleshooting time.

- Complements existing full hardware diagnostics without replacing them.

<a id="rst-data-exposure-and-consumption"></a>

## Data Exposure and Consumption

- The tracked error data consists of per-error-type counts and timestamps of last occurrence.

- This data is stored in the `hwerror_data` array, categorized by error source types like CPU, memory, PCI, CXL, and others.

- It is exposed via vmcoreinfo crash dump notes and can be read using tools like `crash`, `drgn`, or other kernel crash analysis utilities.

- There is no other way to read these data other than from crash dumps.

- These errors are divided by area, which includes CPU, Memory, PCI, CXL and others.

Typical usage example (in drgn REPL):



```python
>>> prog['hwerror_data']
(struct hwerror_info[HWERR_RECOV_MAX]){
    {
        .count = (int)844,
        .timestamp = (time64_t)1752852018,
    },
    ...
}
```

<a id="rst-enabling"></a>

## Enabling

- This feature is enabled when CONFIG_VMCORE_INFO is set.

---

# Input Subsystem

_Peios Kernel / Hardware and drivers / Driver development / Clocks, signals and platform services_

> Reference for Input Subsystem.

<a id="rst-input-subsystem"></a>

<a id="rst-input-core"></a>

## Input core


#### <a id="c-struct-input_value"></a>`struct input_value`

input value representation

**Definition**

```c
struct input_value {
    __u16 type;
    __u16 code;
    __s32 value;
};
```

**Members**

- `type`: type of value (EV_KEY, EV_ABS, etc)
- `code`: the value code
- `value`: the value

#### <a id="c-struct-input_dev"></a>`struct input_dev`

represents an input device

**Definition**

```c
struct input_dev {
    const char *name;
    const char *phys;
    const char *uniq;
    struct input_id id;
    unsigned long propbit[BITS_TO_LONGS(INPUT_PROP_CNT)];
    unsigned long evbit[BITS_TO_LONGS(EV_CNT)];
    unsigned long keybit[BITS_TO_LONGS(KEY_CNT)];
    unsigned long relbit[BITS_TO_LONGS(REL_CNT)];
    unsigned long absbit[BITS_TO_LONGS(ABS_CNT)];
    unsigned long mscbit[BITS_TO_LONGS(MSC_CNT)];
    unsigned long ledbit[BITS_TO_LONGS(LED_CNT)];
    unsigned long sndbit[BITS_TO_LONGS(SND_CNT)];
    unsigned long ffbit[BITS_TO_LONGS(FF_CNT)];
    unsigned long swbit[BITS_TO_LONGS(SW_CNT)];
    unsigned int hint_events_per_packet;
    unsigned int keycodemax;
    unsigned int keycodesize;
    void *keycode;
    int (*setkeycode)(struct input_dev *dev, const struct input_keymap_entry *ke, unsigned int *old_keycode);
    int (*getkeycode)(struct input_dev *dev, struct input_keymap_entry *ke);
    struct ff_device *ff;
    struct input_dev_poller *poller;
    unsigned int repeat_key;
    struct timer_list timer;
    int rep[REP_CNT];
    struct input_mt *mt;
    struct input_absinfo *absinfo;
    unsigned long key[BITS_TO_LONGS(KEY_CNT)];
    unsigned long led[BITS_TO_LONGS(LED_CNT)];
    unsigned long snd[BITS_TO_LONGS(SND_CNT)];
    unsigned long sw[BITS_TO_LONGS(SW_CNT)];
    int (*open)(struct input_dev *dev);
    void (*close)(struct input_dev *dev);
    int (*flush)(struct input_dev *dev, struct file *file);
    int (*event)(struct input_dev *dev, unsigned int type, unsigned int code, int value);
    struct input_handle  *grab;
    spinlock_t event_lock;
    struct mutex mutex;
    unsigned int users;
    bool going_away;
    struct device dev;
    struct list_head        h_list;
    struct list_head        node;
    unsigned int num_vals;
    unsigned int max_vals;
    struct input_value *vals;
    bool devres_managed;
    ktime_t timestamp[INPUT_CLK_MAX];
    bool inhibited;
};
```

**Members**

- `name`: name of the device
- `phys`: physical path to the device in the system hierarchy
- `uniq`: unique identification code for the device (if device has it)
- `id`: id of the device (struct input_id)
- `propbit`: bitmap of device properties and quirks
- `evbit`: bitmap of types of events supported by the device (EV_KEY,
  EV_REL, etc.)
- `keybit`: bitmap of keys/buttons this device has
- `relbit`: bitmap of relative axes for the device
- `absbit`: bitmap of absolute axes for the device
- `mscbit`: bitmap of miscellaneous events supported by the device
- `ledbit`: bitmap of leds present on the device
- `sndbit`: bitmap of sound effects supported by the device
- `ffbit`: bitmap of force feedback effects supported by the device
- `swbit`: bitmap of switches present on the device
- `hint_events_per_packet`: average number of events generated by the
  device in a packet (between EV_SYN/SYN_REPORT events). Used by
  event handlers to estimate size of the buffer needed to hold
  events.
- `keycodemax`: size of keycode table
- `keycodesize`: size of elements in keycode table
- `keycode`: map of scancodes to keycodes for this device
- `setkeycode`: optional method to alter current keymap, used to implement
  sparse keymaps. If not supplied default mechanism will be used.
  The method is being called while holding event_lock and thus must
  not sleep
- `getkeycode`: optional legacy method to retrieve current keymap.
- `ff`: force feedback structure associated with the device if device
  supports force feedback effects
- `poller`: poller structure associated with the device if device is
  set up to use polling mode
- `repeat_key`: stores key code of the last key pressed; used to implement
  software autorepeat
- `timer`: timer for software autorepeat
- `rep`: current values for autorepeat parameters (delay, rate)
- `mt`: pointer to multitouch state
- `absinfo`: array of `struct input_absinfo` elements holding information
  about absolute axes (current value, min, max, flat, fuzz,
  resolution)
- `key`: reflects current state of device's keys/buttons
- `led`: reflects current state of device's LEDs
- `snd`: reflects current state of sound effects
- `sw`: reflects current state of device's switches
- `open`: this method is called when the very first user calls
  [`input_open_device()`](#c-input_open_device). The driver must prepare the device
  to start generating events (start polling thread,
  request an IRQ, submit URB, etc.). The meaning of `open()` is
  to start providing events to the input core.
- `close`: this method is called when the very last user calls
  [`input_close_device()`](#c-input_close_device). The meaning of `close()` is to stop
  providing events to the input core.
- `flush`: purges the device. Most commonly used to get rid of force
  feedback effects loaded into the device when disconnecting
  from it
- `event`: event handler for events sent _to_ the device, like EV_LED
  or EV_SND. The device is expected to carry out the requested
  action (turn on a LED, play sound, etc.) The call is protected
  by **event_lock** and must not sleep
- `grab`: input handle that currently has the device grabbed (via
  EVIOCGRAB ioctl). When a handle grabs a device it becomes sole
  recipient for all input events coming from the device
- `event_lock`: this spinlock is taken when input core receives
  and processes a new event for the device (in [`input_event()`](#c-input_event)).
  Code that accesses and/or modifies parameters of a device
  (such as keymap or absmin, absmax, absfuzz, etc.) after device
  has been registered with input core must take this lock.
- `mutex`: serializes calls to `open()`, `close()` and `flush()` methods
- `users`: stores number of users (input handlers) that opened this
  device. It is used by [`input_open_device()`](#c-input_open_device) and [`input_close_device()`](#c-input_close_device)
  to make sure that dev->`open()` is only called when the first
  user opens device and dev->`close()` is called when the very
  last user closes the device
- `going_away`: marks devices that are in a middle of unregistering and
  causes input_open_device*() fail with -ENODEV.
- `dev`: driver model's view of this device
- `h_list`: list of input handles associated with the device. When
  accessing the list dev->mutex must be held
- `node`: used to place the device onto input_dev_list
- `num_vals`: number of values queued in the current frame
- `max_vals`: maximum number of values queued in a frame
- `vals`: array of values queued in the current frame
- `devres_managed`: indicates that devices is managed with devres framework
  and needs not be explicitly unregistered or freed.
- `timestamp`: storage for a timestamp set by input_set_timestamp called
  by a driver
- `inhibited`: indicates that the input device is inhibited. If that is
  the case then input core ignores any events generated by the device.
  Device's `close()` is called when it is being inhibited and its `open()`
  is called when it is being uninhibited.

#### <a id="c-struct-input_handler"></a>`struct input_handler`

implements one of interfaces for input devices

**Definition**

```c
struct input_handler {
    void *private;
    void (*event)(struct input_handle *handle, unsigned int type, unsigned int code, int value);
    unsigned int (*events)(struct input_handle *handle, struct input_value *vals, unsigned int count);
    bool (*filter)(struct input_handle *handle, unsigned int type, unsigned int code, int value);
    bool (*match)(struct input_handler *handler, struct input_dev *dev);
    int (*connect)(struct input_handler *handler, struct input_dev *dev, const struct input_device_id *id);
    void (*disconnect)(struct input_handle *handle);
    void (*start)(struct input_handle *handle);
    bool passive_observer;
    bool legacy_minors;
    int minor;
    const char *name;
    const struct input_device_id *id_table;
    struct list_head        h_list;
    struct list_head        node;
};
```

**Members**

- `private`: driver-specific data
- `event`: event handler. This method is being called by input core with
  interrupts disabled and dev->event_lock spinlock held and so
  it may not sleep
- `events`: event sequence handler. This method is being called by
  input core with interrupts disabled and dev->event_lock
  spinlock held and so it may not sleep. The method must return
  number of events passed to it.
- `filter`: similar to **event**; separates normal event handlers from
  "filters".
- `match`: called after comparing device's id with handler's id_table
  to perform fine-grained matching between device and handler
- `connect`: called when attaching a handler to an input device
- `disconnect`: disconnects a handler from input device
- `start`: starts handler for given handle. This function is called by
  input core right after `connect()` method and also when a process
  that "grabbed" a device releases it
- `passive_observer`: set to `true` by drivers only interested in observing
  data stream from devices if there are other users present. Such
  drivers will not result in starting underlying hardware device
  when [`input_open_device()`](#c-input_open_device) is called for their handles
- `legacy_minors`: set to `true` by drivers using legacy minor ranges
- `minor`: beginning of range of 32 legacy minors for devices this driver
  can provide
- `name`: name of the handler, to be shown in /proc/bus/input/handlers
- `id_table`: pointer to a table of input_device_ids this driver can
  handle
- `h_list`: list of input handles associated with the handler
- `node`: for placing the driver onto input_handler_list

**Description**

Input handlers attach to input devices and create input handles. There
are likely several handlers attached to any given input device at the
same time. All of them will get their copy of input event generated by
the device.

The very same structure is used to implement input filters. Input core
allows filters to run first and will not pass event to regular handlers
if any of the filters indicate that the event should be filtered (by
returning `true` from their `filter()` method).

Note that input core serializes calls to `connect()` and `disconnect()`
methods.

#### <a id="c-struct-input_handle"></a>`struct input_handle`

links input device with an input handler

**Definition**

```c
struct input_handle {
    void *private;
    int open;
    const char *name;
    struct input_dev *dev;
    struct input_handler *handler;
    unsigned int (*handle_events)(struct input_handle *handle, struct input_value *vals, unsigned int count);
    struct list_head        d_node;
    struct list_head        h_node;
};
```

**Members**

- `private`: handler-specific data
- `open`: counter showing whether the handle is 'open', i.e. should deliver
  events from its device
- `name`: name given to the handle by handler that created it
- `dev`: input device the handle is attached to
- `handler`: handler that works with the device through this handle
- `handle_events`: event sequence handler. It is set up by the input core
  according to event handling method specified in the **handler**. See
  `input_handle_setup_event_handler()`.
  This method is being called by the input core with interrupts disabled
  and dev->event_lock spinlock held and so it may not sleep.
- `d_node`: used to put the handle on device's list of attached handles
- `h_node`: used to put the handle on handler's list of handles from which
  it gets events

#### <a id="c-input_set_events_per_packet"></a>`input_set_events_per_packet()`

```c
void input_set_events_per_packet(struct input_dev *dev, int n_events)
```

tell handlers about the driver event rate

**Parameters**

- `struct input_dev *dev`: the input device used by the driver
- `int n_events`: the average number of events between calls to `input_sync()`

**Description**

If the event rate sent from a device is unusually large, use this
function to set the expected event rate. This will allow handlers
to set up an appropriate buffer size for the event stream, in order
to minimize information loss.

#### <a id="c-struct-ff_device"></a>`struct ff_device`

force-feedback part of an input device

**Definition**

```c
struct ff_device {
    int (*upload)(struct input_dev *dev, struct ff_effect *effect, struct ff_effect *old);
    int (*erase)(struct input_dev *dev, int effect_id);
    int (*playback)(struct input_dev *dev, int effect_id, int value);
    void (*set_gain)(struct input_dev *dev, u16 gain);
    void (*set_autocenter)(struct input_dev *dev, u16 magnitude);
    void (*destroy)(struct ff_device *);
    void *private;
    unsigned long ffbit[BITS_TO_LONGS(FF_CNT)];
    struct mutex mutex;
    int max_effects;
    struct ff_effect *effects;
    struct file *effect_owners[] ;
};
```

**Members**

- `upload`: Called to upload an new effect into device
- `erase`: Called to erase an effect from device
- `playback`: Called to request device to start playing specified effect
- `set_gain`: Called to set specified gain
- `set_autocenter`: Called to auto-center device
- `destroy`: called by input core when parent input device is being
  destroyed
- `private`: driver-specific data, will be freed automatically
- `ffbit`: bitmap of force feedback capabilities truly supported by
  device (not emulated like ones in input_dev->ffbit)
- `mutex`: mutex for serializing access to the device
- `max_effects`: maximum number of effects supported by device
- `effects`: pointer to an array of effects currently loaded into device
- `effect_owners`: array of effect owners; when file handle owning
  an effect gets closed the effect is automatically erased

**Description**

Every force-feedback device must implement `upload()` and `playback()`
methods; `erase()` is optional. `set_gain()` and `set_autocenter()` need
only be implemented if driver sets up FF_GAIN and FF_AUTOCENTER
bits.

Note that `playback()`, `set_gain()` and `set_autocenter()` are called with
dev->event_lock spinlock held and interrupts off and thus may not
sleep.



#### <a id="c-input_event"></a>`input_event()`

```c
void input_event(struct input_dev *dev, unsigned int type, unsigned int code, int value)
```

report new input event

**Parameters**

- `struct input_dev *dev`: device that generated the event
- `unsigned int type`: type of the event
- `unsigned int code`: event code
- `int value`: value of the event

**Description**

This function should be used by drivers implementing various input
devices to report input events. See also [`input_inject_event()`](#c-input_inject_event).

**NOTE**

[`input_event()`](#c-input_event) may be safely used right after input device was
allocated with [`input_allocate_device()`](#c-input_allocate_device), even before it is registered
with [`input_register_device()`](#c-input_register_device), but the event will not reach any of the
input handlers. Such early invocation of [`input_event()`](#c-input_event) may be used
to 'seed' initial state of a switch or initial position of absolute
axis, etc.

#### <a id="c-input_inject_event"></a>`input_inject_event()`

```c
void input_inject_event(struct input_handle *handle, unsigned int type, unsigned int code, int value)
```

send input event from input handler

**Parameters**

- `struct input_handle *handle`: input handle to send event through
- `unsigned int type`: type of the event
- `unsigned int code`: event code
- `int value`: value of the event

**Description**

Similar to [`input_event()`](#c-input_event) but will ignore event if device is
"grabbed" and handle injecting event is not the one that owns
the device.

#### <a id="c-input_alloc_absinfo"></a>`input_alloc_absinfo()`

```c
void input_alloc_absinfo(struct input_dev *dev)
```

allocates array of input_absinfo structs

**Parameters**

- `struct input_dev *dev`: the input device emitting absolute events

**Description**

If the absinfo struct the caller asked for is already allocated, this
functions will not do anything.

#### <a id="c-input_copy_abs"></a>`input_copy_abs()`

```c
void input_copy_abs(struct input_dev *dst, unsigned int dst_axis, const struct input_dev *src, unsigned int src_axis)
```

Copy absinfo from one input_dev to another

**Parameters**

- `struct input_dev *dst`: Destination input device to copy the abs settings to
- `unsigned int dst_axis`: ABS_* value selecting the destination axis
- `const struct input_dev *src`: Source input device to copy the abs settings from
- `unsigned int src_axis`: ABS_* value selecting the source axis

**Description**

Set absinfo for the selected destination axis by copying it from
the specified source input device's source axis.
This is useful to e.g. setup a pen/stylus input-device for combined
touchscreen/pen hardware where the pen uses the same coordinates as
the touchscreen.

#### <a id="c-input_grab_device"></a>`input_grab_device()`

```c
int input_grab_device(struct input_handle *handle)
```

grabs device for exclusive use

**Parameters**

- `struct input_handle *handle`: input handle that wants to own the device

**Description**

When a device is grabbed by an input handle all events generated by
the device are delivered only to this handle. Also events injected
by other input handles are ignored while device is grabbed.

#### <a id="c-input_release_device"></a>`input_release_device()`

```c
void input_release_device(struct input_handle *handle)
```

release previously grabbed device

**Parameters**

- `struct input_handle *handle`: input handle that owns the device

**Description**

Releases previously grabbed device so that other input handles can
start receiving input events. Upon release all handlers attached
to the device have their `start()` method called so they have a change
to synchronize device state with the rest of the system.

#### <a id="c-input_open_device"></a>`input_open_device()`

```c
int input_open_device(struct input_handle *handle)
```

open input device

**Parameters**

- `struct input_handle *handle`: handle through which device is being accessed

**Description**

This function should be called by input handlers when they
want to start receive events from given input device.

#### <a id="c-input_close_device"></a>`input_close_device()`

```c
void input_close_device(struct input_handle *handle)
```

close input device

**Parameters**

- `struct input_handle *handle`: handle through which device is being accessed

**Description**

This function should be called by input handlers when they
want to stop receive events from given input device.

#### <a id="c-input_scancode_to_scalar"></a>`input_scancode_to_scalar()`

```c
int input_scancode_to_scalar(const struct input_keymap_entry *ke, unsigned int *scancode)
```

converts scancode in `struct input_keymap_entry`

**Parameters**

- `const struct input_keymap_entry *ke`: keymap entry containing scancode to be converted.
- `unsigned int *scancode`: pointer to the location where converted scancode should
  be stored.

**Description**

This function is used to convert scancode stored in `struct keymap_entry`
into scalar form understood by legacy keymap handling methods. These
methods expect scancodes to be represented as 'unsigned int'.

#### <a id="c-input_get_keycode"></a>`input_get_keycode()`

```c
int input_get_keycode(struct input_dev *dev, struct input_keymap_entry *ke)
```

retrieve keycode currently mapped to a given scancode

**Parameters**

- `struct input_dev *dev`: input device which keymap is being queried
- `struct input_keymap_entry *ke`: keymap entry

**Description**

This function should be called by anyone interested in retrieving current
keymap. Presently evdev handlers use it.

#### <a id="c-input_set_keycode"></a>`input_set_keycode()`

```c
int input_set_keycode(struct input_dev *dev, const struct input_keymap_entry *ke)
```

attribute a keycode to a given scancode

**Parameters**

- `struct input_dev *dev`: input device which keymap is being updated
- `const struct input_keymap_entry *ke`: new keymap entry

**Description**

This function should be called by anyone needing to update current
keymap. Presently keyboard and evdev handlers use it.

#### <a id="c-input_reset_device"></a>`input_reset_device()`

```c
void input_reset_device(struct input_dev *dev)
```

reset/restore the state of input device

**Parameters**

- `struct input_dev *dev`: input device whose state needs to be reset

**Description**

This function tries to reset the state of an opened input device and
bring internal state and state if the hardware in sync with each other.
We mark all keys as released, restore LED state, repeat rate, etc.

#### <a id="c-input_allocate_device"></a>`input_allocate_device()`

```c
struct input_dev * input_allocate_device(void)
```

allocate memory for new input device

**Parameters**

- `void`: no arguments

**Description**

Returns prepared struct input_dev or `NULL`.

**NOTE**

Use [`input_free_device()`](#c-input_free_device) to free devices that have not been
registered; [`input_unregister_device()`](#c-input_unregister_device) should be used for already
registered devices.

#### <a id="c-devm_input_allocate_device"></a>`devm_input_allocate_device()`

```c
struct input_dev * devm_input_allocate_device(struct device *dev)
```

allocate managed input device

**Parameters**

- `struct device *dev`: device owning the input device being created

**Description**

Returns prepared struct input_dev or `NULL`.

Managed input devices do not need to be explicitly unregistered or
freed as it will be done automatically when owner device unbinds from
its driver (or binding fails). Once managed input device is allocated,
it is ready to be set up and registered in the same fashion as regular
input device. There are no special devm_input_device_\[un\]`register()`
variants, regular ones work with both managed and unmanaged devices,
should you need them. In most cases however, managed input device need
not be explicitly unregistered or freed.

**NOTE**

the owner device is set up as parent of input device and users
should not override it.

#### <a id="c-input_free_device"></a>`input_free_device()`

```c
void input_free_device(struct input_dev *dev)
```

free memory occupied by input_dev structure

**Parameters**

- `struct input_dev *dev`: input device to free

**Description**

This function should only be used if [`input_register_device()`](#c-input_register_device)
was not called yet or if it failed. Once device was registered
use [`input_unregister_device()`](#c-input_unregister_device) and memory will be freed once last
reference to the device is dropped.

Device should be allocated by [`input_allocate_device()`](#c-input_allocate_device).

**NOTE**

If there are references to the input device then memory
will not be freed until last reference is dropped.

#### <a id="c-input_set_timestamp"></a>`input_set_timestamp()`

```c
void input_set_timestamp(struct input_dev *dev, ktime_t timestamp)
```

set timestamp for input events

**Parameters**

- `struct input_dev *dev`: input device to set timestamp for
- `ktime_t timestamp`: the time at which the event has occurred
  in CLOCK_MONOTONIC

**Description**

This function is intended to provide to the input system a more
accurate time of when an event actually occurred. The driver should
call this function as soon as a timestamp is acquired ensuring
clock conversions in input_set_timestamp are done correctly.

The system entering suspend state between timestamp acquisition and
calling input_set_timestamp can result in inaccurate conversions.

#### <a id="c-input_get_timestamp"></a>`input_get_timestamp()`

```c
ktime_t * input_get_timestamp(struct input_dev *dev)
```

get timestamp for input events

**Parameters**

- `struct input_dev *dev`: input device to get timestamp from

**Description**

A valid timestamp is a timestamp of non-zero value.

#### <a id="c-input_set_capability"></a>`input_set_capability()`

```c
void input_set_capability(struct input_dev *dev, unsigned int type, unsigned int code)
```

mark device as capable of a certain event

**Parameters**

- `struct input_dev *dev`: device that is capable of emitting or accepting event
- `unsigned int type`: type of the event (EV_KEY, EV_REL, etc...)
- `unsigned int code`: event code

**Description**

In addition to setting up corresponding bit in appropriate capability
bitmap the function also adjusts dev->evbit.

#### <a id="c-input_enable_softrepeat"></a>`input_enable_softrepeat()`

```c
void input_enable_softrepeat(struct input_dev *dev, int delay, int period)
```

enable software autorepeat

**Parameters**

- `struct input_dev *dev`: input device
- `int delay`: repeat delay
- `int period`: repeat period

**Description**

Enable software autorepeat on the input device.

#### <a id="c-input_register_device"></a>`input_register_device()`

```c
int input_register_device(struct input_dev *dev)
```

register device with input core

**Parameters**

- `struct input_dev *dev`: device to be registered

**Description**

This function registers device with input core. The device must be
allocated with [`input_allocate_device()`](#c-input_allocate_device) and all it's capabilities
set up before registering.
If function fails the device must be freed with [`input_free_device()`](#c-input_free_device).
Once device has been successfully registered it can be unregistered
with [`input_unregister_device()`](#c-input_unregister_device); [`input_free_device()`](#c-input_free_device) should not be
called in this case.

Note that this function is also used to register managed input devices
(ones allocated with [`devm_input_allocate_device()`](#c-devm_input_allocate_device)). Such managed input
devices need not be explicitly unregistered or freed, their tear down
is controlled by the devres infrastructure. It is also worth noting
that tear down of managed input devices is internally a 2-step process:
registered managed input device is first unregistered, but stays in
memory and can still handle [`input_event()`](#c-input_event) calls (although events will
not be delivered anywhere). The freeing of managed input device will
happen later, when devres stack is unwound to the point where device
allocation was made.

#### <a id="c-input_unregister_device"></a>`input_unregister_device()`

```c
void input_unregister_device(struct input_dev *dev)
```

unregister previously registered device

**Parameters**

- `struct input_dev *dev`: device to be unregistered

**Description**

This function unregisters an input device. Once device is unregistered
the caller should not try to access it as it may get freed at any moment.

#### <a id="c-input_register_handler"></a>`input_register_handler()`

```c
int input_register_handler(struct input_handler *handler)
```

register a new input handler

**Parameters**

- `struct input_handler *handler`: handler to be registered

**Description**

This function registers a new input handler (interface) for input
devices in the system and attaches it to all input devices that
are compatible with the handler.

#### <a id="c-input_unregister_handler"></a>`input_unregister_handler()`

```c
void input_unregister_handler(struct input_handler *handler)
```

unregisters an input handler

**Parameters**

- `struct input_handler *handler`: handler to be unregistered

**Description**

This function disconnects a handler from its input devices and
removes it from lists of known handlers.

#### <a id="c-input_handler_for_each_handle"></a>`input_handler_for_each_handle()`

```c
int input_handler_for_each_handle(struct input_handler *handler, void *data, int (*fn)(struct input_handle *, void *))
```

handle iterator

**Parameters**

- `struct input_handler *handler`: input handler to iterate
- `void *data`: data for the callback
- `int (*fn)(struct input_handle *, void *)`: function to be called for each handle

**Description**

Iterate over **bus**'s list of devices, and call **fn** for each, passing
it **data** and stop when **fn** returns a non-zero value. The function is
using RCU to traverse the list and therefore may be using in atomic
contexts. The **fn** callback is invoked from RCU critical section and
thus must not sleep.

#### <a id="c-input_register_handle"></a>`input_register_handle()`

```c
int input_register_handle(struct input_handle *handle)
```

register a new input handle

**Parameters**

- `struct input_handle *handle`: handle to register

**Description**

This function puts a new input handle onto device's
and handler's lists so that events can flow through
it once it is opened using [`input_open_device()`](#c-input_open_device).

This function is supposed to be called from handler's
`connect()` method.

#### <a id="c-input_unregister_handle"></a>`input_unregister_handle()`

```c
void input_unregister_handle(struct input_handle *handle)
```

unregister an input handle

**Parameters**

- `struct input_handle *handle`: handle to unregister

**Description**

This function removes input handle from device's
and handler's lists.

This function is supposed to be called from handler's
`disconnect()` method.

#### <a id="c-input_get_new_minor"></a>`input_get_new_minor()`

```c
int input_get_new_minor(int legacy_base, unsigned int legacy_num, bool allow_dynamic)
```

allocates a new input minor number

**Parameters**

- `int legacy_base`: beginning or the legacy range to be searched
- `unsigned int legacy_num`: size of legacy range
- `bool allow_dynamic`: whether we can also take ID from the dynamic range

**Description**

This function allocates a new device minor for from input major namespace.
Caller can request legacy minor by specifying **legacy_base** and **legacy_num**
parameters and whether ID can be allocated from dynamic range if there are
no free IDs in legacy range.

#### <a id="c-input_free_minor"></a>`input_free_minor()`

```c
void input_free_minor(unsigned int minor)
```

release previously allocated minor

**Parameters**

- `unsigned int minor`: minor to be released

**Description**

This function releases previously allocated input minor so that it can be
reused later.



#### <a id="c-input_ff_upload"></a>`input_ff_upload()`

```c
int input_ff_upload(struct input_dev *dev, struct ff_effect *effect, struct file *file)
```

upload effect into force-feedback device

**Parameters**

- `struct input_dev *dev`: input device
- `struct ff_effect *effect`: effect to be uploaded
- `struct file *file`: owner of the effect

#### <a id="c-input_ff_erase"></a>`input_ff_erase()`

```c
int input_ff_erase(struct input_dev *dev, int effect_id, struct file *file)
```

erase a force-feedback effect from device

**Parameters**

- `struct input_dev *dev`: input device to erase effect from
- `int effect_id`: id of the effect to be erased
- `struct file *file`: purported owner of the request

**Description**

This function erases a force-feedback effect from specified device.
The effect will only be erased if it was uploaded through the same
file handle that is requesting erase.

#### <a id="c-input_ff_event"></a>`input_ff_event()`

```c
int input_ff_event(struct input_dev *dev, unsigned int type, unsigned int code, int value)
```

generic handler for force-feedback events

**Parameters**

- `struct input_dev *dev`: input device to send the effect to
- `unsigned int type`: event type (anything but EV_FF is ignored)
- `unsigned int code`: event code
- `int value`: event value

#### <a id="c-input_ff_create"></a>`input_ff_create()`

```c
int input_ff_create(struct input_dev *dev, unsigned int max_effects)
```

create force-feedback device

**Parameters**

- `struct input_dev *dev`: input device supporting force-feedback
- `unsigned int max_effects`: maximum number of effects supported by the device

**Description**

This function allocates all necessary memory for a force feedback
portion of an input device and installs all default handlers.
**dev->ffbit** should be already set up before calling this function.
Once ff device is created you need to setup its upload, erase,
playback and other handlers before registering input device

#### <a id="c-input_ff_destroy"></a>`input_ff_destroy()`

```c
void input_ff_destroy(struct input_dev *dev)
```

frees force feedback portion of input device

**Parameters**

- `struct input_dev *dev`: input device supporting force feedback

**Description**

This function is only needed in error path as input core will
automatically free force feedback structures when device is
destroyed.



#### <a id="c-input_ff_create_memless"></a>`input_ff_create_memless()`

```c
int input_ff_create_memless(struct input_dev *dev, void *data, int (*play_effect)(struct input_dev *, void *, struct ff_effect *))
```

create memoryless force-feedback device

**Parameters**

- `struct input_dev *dev`: input device supporting force-feedback
- `void *data`: driver-specific data to be passed into **play_effect**
- `int (*play_effect)(struct input_dev *, void *, struct ff_effect *)`: driver-specific method for playing FF effect


<a id="rst-multitouch-library"></a>

## Multitouch Library


#### <a id="c-struct-input_mt_slot"></a>`struct input_mt_slot`

represents the state of an input MT slot

**Definition**

```c
struct input_mt_slot {
    int abs[ABS_MT_LAST - ABS_MT_FIRST + 1];
    unsigned int frame;
    unsigned int key;
};
```

**Members**

- `abs`: holds current values of ABS_MT axes for this slot
- `frame`: last frame at which [`input_mt_report_slot_state()`](#c-input_mt_report_slot_state) was called
- `key`: optional driver designation of this slot

#### <a id="c-struct-input_mt"></a>`struct input_mt`

state of tracked contacts

**Definition**

```c
struct input_mt {
    int trkid;
    int num_slots;
    int slot;
    unsigned int flags;
    unsigned int frame;
    int *red;
    struct input_mt_slot slots[] ;
};
```

**Members**

- `trkid`: stores MT tracking ID for the next contact
- `num_slots`: number of MT slots the device uses
- `slot`: MT slot currently being transmitted
- `flags`: input_mt operation flags
- `frame`: increases every time [`input_mt_sync_frame()`](#c-input_mt_sync_frame) is called
- `red`: reduced cost matrix for in-kernel tracking
- `slots`: array of slots holding current values of tracked contacts

#### <a id="c-struct-input_mt_pos"></a>`struct input_mt_pos`

contact position

**Definition**

```c
struct input_mt_pos {
    s16 x, y;
};
```

**Members**

- `x`: horizontal coordinate
- `y`: vertical coordinate



#### <a id="c-input_mt_init_slots"></a>`input_mt_init_slots()`

```c
int input_mt_init_slots(struct input_dev *dev, unsigned int num_slots, unsigned int flags)
```

initialize MT input slots

**Parameters**

- `struct input_dev *dev`: input device supporting MT events and finger tracking
- `unsigned int num_slots`: number of slots used by the device
- `unsigned int flags`: mt tasks to handle in core

**Description**

This function allocates all necessary memory for MT slot handling
in the input device, prepares the ABS_MT_SLOT and
ABS_MT_TRACKING_ID events for use and sets up appropriate buffers.
Depending on the flags set, it also performs pointer emulation and
frame synchronization.

May be called repeatedly. Returns -EINVAL if attempting to
reinitialize with a different number of slots.

#### <a id="c-input_mt_destroy_slots"></a>`input_mt_destroy_slots()`

```c
void input_mt_destroy_slots(struct input_dev *dev)
```

frees the MT slots of the input device

**Parameters**

- `struct input_dev *dev`: input device with allocated MT slots

**Description**

This function is only needed in error path as the input core will
automatically free the MT slots when the device is destroyed.

#### <a id="c-input_mt_report_slot_state"></a>`input_mt_report_slot_state()`

```c
bool input_mt_report_slot_state(struct input_dev *dev, unsigned int tool_type, bool active)
```

report contact state

**Parameters**

- `struct input_dev *dev`: input device with allocated MT slots
- `unsigned int tool_type`: the tool type to use in this slot
- `bool active`: true if contact is active, false otherwise

**Description**

Reports a contact via ABS_MT_TRACKING_ID, and optionally
ABS_MT_TOOL_TYPE. If active is true and the slot is currently
inactive, or if the tool type is changed, a new tracking id is
assigned to the slot. The tool type is only reported if the
corresponding absbit field is set.

Returns true if contact is active.

#### <a id="c-input_mt_report_finger_count"></a>`input_mt_report_finger_count()`

```c
void input_mt_report_finger_count(struct input_dev *dev, int count)
```

report contact count

**Parameters**

- `struct input_dev *dev`: input device with allocated MT slots
- `int count`: the number of contacts

**Description**

Reports the contact count via BTN_TOOL_FINGER, BTN_TOOL_DOUBLETAP,
BTN_TOOL_TRIPLETAP and BTN_TOOL_QUADTAP.

The input core ensures only the KEY events already setup for
this device will produce output.

#### <a id="c-input_mt_report_pointer_emulation"></a>`input_mt_report_pointer_emulation()`

```c
void input_mt_report_pointer_emulation(struct input_dev *dev, bool use_count)
```

common pointer emulation

**Parameters**

- `struct input_dev *dev`: input device with allocated MT slots
- `bool use_count`: report number of active contacts as finger count

**Description**

Performs legacy pointer emulation via BTN_TOUCH, ABS_X, ABS_Y and
ABS_PRESSURE. Touchpad finger count is emulated if use_count is true.

The input core ensures only the KEY and ABS axes already setup for
this device will produce output.

#### <a id="c-input_mt_drop_unused"></a>`input_mt_drop_unused()`

```c
void input_mt_drop_unused(struct input_dev *dev)
```

Inactivate slots not seen in this frame

**Parameters**

- `struct input_dev *dev`: input device with allocated MT slots

**Description**

Lift all slots not seen since the last call to this function.

#### <a id="c-input_mt_sync_frame"></a>`input_mt_sync_frame()`

```c
void input_mt_sync_frame(struct input_dev *dev)
```

synchronize mt frame

**Parameters**

- `struct input_dev *dev`: input device with allocated MT slots

**Description**

Close the frame and prepare the internal state for a new one.
Depending on the flags, marks unused slots as inactive and performs
pointer emulation.

#### <a id="c-input_mt_assign_slots"></a>`input_mt_assign_slots()`

```c
int input_mt_assign_slots(struct input_dev *dev, int *slots, const struct input_mt_pos *pos, int num_pos, int dmax)
```

perform a best-match assignment

**Parameters**

- `struct input_dev *dev`: input device with allocated MT slots
- `int *slots`: the slot assignment to be filled
- `const struct input_mt_pos *pos`: the position array to match
- `int num_pos`: number of positions
- `int dmax`: maximum ABS_MT_POSITION displacement (zero for infinite)

**Description**

Performs a best match against the current contacts and returns
the slot assignment list. New contacts are assigned to unused
slots.

The assignments are balanced so that all coordinate displacements are
below the euclidian distance dmax. If no such assignment can be found,
some contacts are assigned to unused slots.

Returns zero on success, or negative error in case of failure.

#### <a id="c-input_mt_get_slot_by_key"></a>`input_mt_get_slot_by_key()`

```c
int input_mt_get_slot_by_key(struct input_dev *dev, int key)
```

return slot matching key

**Parameters**

- `struct input_dev *dev`: input device with allocated MT slots
- `int key`: the key of the sought slot

**Description**

Returns the slot of the given key, if it exists, otherwise
set the key on the first unused slot and return.

If no available slot can be found, -1 is returned.
Note that for this function to work properly, [`input_mt_sync_frame()`](#c-input_mt_sync_frame) has
to be called at each frame.


<a id="rst-matrix-keyboards-keypads"></a>

## Matrix keyboards/keypads


#### <a id="c-struct-matrix_keymap_data"></a>`struct matrix_keymap_data`

keymap for matrix keyboards

**Definition**

```c
struct matrix_keymap_data {
    const uint32_t *keymap;
    unsigned int    keymap_size;
};
```

**Members**

- `keymap`: pointer to array of uint32 values encoded with `KEY()` macro
  representing keymap
- `keymap_size`: number of entries (initialized) in this keymap

**Description**

This structure is supposed to be used by platform code to supply
keymaps to drivers that implement matrix-like keypads/keyboards.


<a id="rst-sparse-keymap-support"></a>

## Sparse keymap support


#### <a id="c-struct-key_entry"></a>`struct key_entry`

keymap entry for use in sparse keymap

**Definition**

```c
struct key_entry {
    int type;
    u32 code;
    union {
        u16 keycode;
        struct {
            u8 code;
            u8 value;
        } sw;
    };
};
```

**Members**

- `type`: Type of the key entry (KE_KEY, KE_SW, KE_VSW, KE_END);
  drivers are allowed to extend the list with their own
  private definitions.
- `code`: Device-specific data identifying the button/switch
- `{unnamed_union}`: anonymous
- `keycode`: KEY_* code assigned to a key/button
- `sw`: struct with code/value used by KE_SW and KE_VSW
- `sw.code`: SW_* code assigned to a switch
- `sw.value`: Value that should be sent in an input even when KE_SW
  switch is toggled. KE_VSW switches ignore this field and
  expect driver to supply value for the event.

**Description**

This structure defines an entry in a sparse keymap used by some
input devices for which traditional table-based approach is not
suitable.



#### <a id="c-sparse_keymap_entry_from_scancode"></a>`sparse_keymap_entry_from_scancode()`

```c
struct key_entry * sparse_keymap_entry_from_scancode(struct input_dev *dev, unsigned int code)
```

perform sparse keymap lookup

**Parameters**

- `struct input_dev *dev`: Input device using sparse keymap
- `unsigned int code`: Scan code

**Description**

This function is used to perform [`struct key_entry`](#c-struct-key_entry) lookup in an
input device using sparse keymap.

#### <a id="c-sparse_keymap_entry_from_keycode"></a>`sparse_keymap_entry_from_keycode()`

```c
struct key_entry * sparse_keymap_entry_from_keycode(struct input_dev *dev, unsigned int keycode)
```

perform sparse keymap lookup

**Parameters**

- `struct input_dev *dev`: Input device using sparse keymap
- `unsigned int keycode`: Key code

**Description**

This function is used to perform [`struct key_entry`](#c-struct-key_entry) lookup in an
input device using sparse keymap.

#### <a id="c-sparse_keymap_setup"></a>`sparse_keymap_setup()`

```c
int sparse_keymap_setup(struct input_dev *dev, const struct key_entry *keymap, int (*setup)(struct input_dev *, struct key_entry *))
```

set up sparse keymap for an input device

**Parameters**

- `struct input_dev *dev`: Input device
- `const struct key_entry *keymap`: Keymap in form of array of [`key_entry`](#c-struct-key_entry) structures ending
  with `KE_END` type entry
- `int (*setup)(struct input_dev *, struct key_entry *)`: Function that can be used to adjust keymap entries
  depending on device's needs, may be `NULL`

**Description**

The function calculates size and allocates copy of the original
keymap after which sets up input device event bits appropriately.
The allocated copy of the keymap is automatically freed when it
is no longer needed.

#### <a id="c-sparse_keymap_report_entry"></a>`sparse_keymap_report_entry()`

```c
void sparse_keymap_report_entry(struct input_dev *dev, const struct key_entry *ke, unsigned int value, bool autorelease)
```

report event corresponding to given key entry

**Parameters**

- `struct input_dev *dev`: Input device for which event should be reported
- `const struct key_entry *ke`: key entry describing event
- `unsigned int value`: Value that should be reported (ignored by `KE_SW` entries)
- `bool autorelease`: Signals whether release event should be emitted for `KE_KEY`
  entries right after reporting press event, ignored by all other
  entries

**Description**

This function is used to report input event described by given
[`struct key_entry`](#c-struct-key_entry).

#### <a id="c-sparse_keymap_report_event"></a>`sparse_keymap_report_event()`

```c
bool sparse_keymap_report_event(struct input_dev *dev, unsigned int code, unsigned int value, bool autorelease)
```

report event corresponding to given scancode

**Parameters**

- `struct input_dev *dev`: Input device using sparse keymap
- `unsigned int code`: Scan code
- `unsigned int value`: Value that should be reported (ignored by `KE_SW` entries)
- `bool autorelease`: Signals whether release event should be emitted for `KE_KEY`
  entries right after reporting press event, ignored by all other
  entries

**Description**

This function is used to perform lookup in an input device using sparse
keymap and report corresponding event. Returns `true` if lookup was
successful and `false` otherwise.


<a id="rst-ps-2-protocol-support"></a>

## PS/2 protocol support


#### <a id="c-enum-ps2_disposition"></a>`enum ps2_disposition`

indicates how received byte should be handled

**Constants**

- `PS2_PROCESS`: pass to the main protocol handler, process normally
- `PS2_IGNORE`: skip the byte
- `PS2_ERROR`: do not process the byte, abort command in progress

#### <a id="c-struct-ps2dev"></a>`struct ps2dev`

represents a device using PS/2 protocol

**Definition**

```c
struct ps2dev {
    struct serio *serio;
    struct mutex cmd_mutex;
    wait_queue_head_t wait;
    unsigned long flags;
    u8 cmdbuf[8];
    u8 cmdcnt;
    u8 nak;
    ps2_pre_receive_handler_t pre_receive_handler;
    ps2_receive_handler_t receive_handler;
};
```

**Members**

- `serio`: a serio port used by the PS/2 device
- `cmd_mutex`: a mutex ensuring that only one command is executing at a time
- `wait`: a waitqueue used to signal completion from the serio interrupt handler
- `flags`: various internal flags indicating stages of PS/2 command execution
- `cmdbuf`: buffer holding command response
- `cmdcnt`: outstanding number of bytes of the command response
- `nak`: a byte transmitted by the device when it refuses command
- `pre_receive_handler`: checks communication errors and returns disposition
  ([`enum ps2_disposition`](#c-enum-ps2_disposition)) of the received data byte
- `receive_handler`: main handler of particular PS/2 protocol, such as keyboard
  or mouse protocol



#### <a id="c-ps2_sendbyte"></a>`ps2_sendbyte()`

```c
int ps2_sendbyte(struct ps2dev *ps2dev, u8 byte, unsigned int timeout)
```

sends a byte to the device and wait for acknowledgement

**Parameters**

- `struct ps2dev *ps2dev`: a PS/2 device to send the data to
- `u8 byte`: data to be sent to the device
- `unsigned int timeout`: timeout for sending the data and receiving an acknowledge

**Description**

The function doesn't handle retransmission, the caller is expected to handle
it when needed.

[`ps2_sendbyte()`](#c-ps2_sendbyte) can only be called from a process context.

#### <a id="c-ps2_begin_command"></a>`ps2_begin_command()`

```c
void ps2_begin_command(struct ps2dev *ps2dev)
```

mark beginning of execution of a complex command

**Parameters**

- `struct ps2dev *ps2dev`: a PS/2 device executing the command

**Description**

Serializes a complex/compound command. Once command is finished
[`ps2_end_command()`](#c-ps2_end_command) should be called.

#### <a id="c-ps2_end_command"></a>`ps2_end_command()`

```c
void ps2_end_command(struct ps2dev *ps2dev)
```

mark end of execution of a complex command

**Parameters**

- `struct ps2dev *ps2dev`: a PS/2 device executing the command

#### <a id="c-ps2_drain"></a>`ps2_drain()`

```c
void ps2_drain(struct ps2dev *ps2dev, size_t maxbytes, unsigned int timeout)
```

waits for device to transmit requested number of bytes and discards them

**Parameters**

- `struct ps2dev *ps2dev`: the PS/2 device that should be drained
- `size_t maxbytes`: maximum number of bytes to be drained
- `unsigned int timeout`: time to drain the device

#### <a id="c-ps2_is_keyboard_id"></a>`ps2_is_keyboard_id()`

```c
bool ps2_is_keyboard_id(u8 id_byte)
```

checks received ID byte against the list of known keyboard IDs

**Parameters**

- `u8 id_byte`: data byte that should be checked

#### <a id="c-__ps2_command"></a>`__ps2_command()`

```c
int __ps2_command(struct ps2dev *ps2dev, u8 *param, unsigned int command)
```

send a command to PS/2 device

**Parameters**

- `struct ps2dev *ps2dev`: the PS/2 device that should execute the command
- `u8 *param`: a buffer containing parameters to be sent along with the command,
  or place where the results of the command execution will be deposited,
  or both
- `unsigned int command`: command word that encodes the command itself, as well as number of
  additional parameter bytes that should be sent to the device and expected
  length of the command response

**Description**

Not serialized. Callers should use [`ps2_begin_command()`](#c-ps2_begin_command) and [`ps2_end_command()`](#c-ps2_end_command)
to ensure proper serialization for complex commands.

#### <a id="c-ps2_command"></a>`ps2_command()`

```c
int ps2_command(struct ps2dev *ps2dev, u8 *param, unsigned int command)
```

send a command to PS/2 device

**Parameters**

- `struct ps2dev *ps2dev`: the PS/2 device that should execute the command
- `u8 *param`: a buffer containing parameters to be sent along with the command,
  or place where the results of the command execution will be deposited,
  or both
- `unsigned int command`: command word that encodes the command itself, as well as number of
  additional parameter bytes that should be sent to the device and expected
  length of the command response

**Note**

[`ps2_command()`](#c-ps2_command) serializes the command execution so that only one
command can be executed at a time for either individual port or the entire
8042 controller.

#### <a id="c-ps2_sliced_command"></a>`ps2_sliced_command()`

```c
int ps2_sliced_command(struct ps2dev *ps2dev, u8 command)
```

sends an extended PS/2 command to a mouse

**Parameters**

- `struct ps2dev *ps2dev`: the PS/2 device that should execute the command
- `u8 command`: command byte

**Description**

The command is sent using "sliced" syntax understood by advanced devices,
such as Logitech or Synaptics touchpads. The command is encoded as:
0xE6 0xE8 rr 0xE8 ss 0xE8 tt 0xE8 uu where (rr*64)+(ss*16)+(tt*4)+uu
is the command.

#### <a id="c-ps2_init"></a>`ps2_init()`

```c
void ps2_init(struct ps2dev *ps2dev, struct serio *serio, ps2_pre_receive_handler_t pre_receive_handler, ps2_receive_handler_t receive_handler)
```

initializes ps2dev structure

**Parameters**

- `struct ps2dev *ps2dev`: structure to be initialized
- `struct serio *serio`: serio port associated with the PS/2 device
- `ps2_pre_receive_handler_t pre_receive_handler`: validation handler to check basic communication state
- `ps2_receive_handler_t receive_handler`: main protocol handler

**Description**

Prepares ps2dev structure for use in drivers for PS/2 devices.

#### <a id="c-ps2_interrupt"></a>`ps2_interrupt()`

```c
irqreturn_t ps2_interrupt(struct serio *serio, u8 data, unsigned int flags)
```

common interrupt handler for PS/2 devices

**Parameters**

- `struct serio *serio`: serio port for the device
- `u8 data`: a data byte received from the device
- `unsigned int flags`: flags such as `SERIO_PARITY` or `SERIO_TIMEOUT` indicating state of
  the data transfer

**Description**

[`ps2_interrupt()`](#c-ps2_interrupt) invokes pre-receive handler, optionally handles command
acknowledgement and response from the device, and finally passes the data
to the main protocol handler for future processing.

---

# Generic System Interconnect Subsystem

_Peios Kernel / Hardware and drivers / Driver development / Clocks, signals and platform services_

> This framework is designed to provide a standard kernel interface to control the settings of the interconnects on an SoC. These settings can be throughput, latency and priority between multiple interconnected devices or functional blocks.…

<a id="rst-generic-system-interconnect-subsystem"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-introduction"></a>

## Introduction

This framework is designed to provide a standard kernel interface to control the settings of the interconnects on an SoC. These settings can be throughput, latency and priority between multiple interconnected devices or functional blocks. This can be controlled dynamically in order to save power or provide maximum performance.

The interconnect bus is hardware with configurable parameters, which can be set on a data path according to the requests received from various drivers. An example of interconnect buses are the interconnects between various components or functional blocks in chipsets. There can be multiple interconnects on an SoC that can be multi-tiered.

Below is a simplified diagram of a real-world SoC interconnect bus topology.



```text
+----------------+    +----------------+
| HW Accelerator |--->|      M NoC     |<---------------+
+----------------+    +----------------+                |
                        |      |                    +------------+
 +-----+  +-------------+      V       +------+     |            |
 | DDR |  |                +--------+  | PCIe |     |            |
 +-----+  |                | Slaves |  +------+     |            |
   ^ ^    |                +--------+     |         |   C NoC    |
   | |    V                               V         |            |
+------------------+   +------------------------+   |            |   +-----+
|                  |-->|                        |-->|            |-->| CPU |
|                  |-->|                        |<--|            |   +-----+
|     Mem NoC      |   |         S NoC          |   +------------+
|                  |<--|                        |---------+    |
|                  |<--|                        |<------+ |    |   +--------+
+------------------+   +------------------------+       | |    +-->| Slaves |
  ^  ^    ^    ^          ^                             | |        +--------+
  |  |    |    |          |                             | V
+------+  |  +-----+   +-----+  +---------+   +----------------+   +--------+
| CPUs |  |  | GPU |   | DSP |  | Masters |-->|       P NoC    |-->| Slaves |
+------+  |  +-----+   +-----+  +---------+   +----------------+   +--------+
          |
      +-------+
      | Modem |
      +-------+
```

<a id="rst-terminology"></a>

## Terminology

Interconnect provider is the software definition of the interconnect hardware. The interconnect providers on the above diagram are M NoC, S NoC, C NoC, P NoC and Mem NoC.

Interconnect node is the software definition of the interconnect hardware port. Each interconnect provider consists of multiple interconnect nodes, which are connected to other SoC components including other interconnect providers. The point on the diagram where the CPUs connect to the memory is called an interconnect node, which belongs to the Mem NoC interconnect provider.

Interconnect endpoints are the first or the last element of the path. Every endpoint is a node, but not every node is an endpoint.

Interconnect path is everything between two endpoints including all the nodes that have to be traversed to reach from a source to destination node. It may include multiple master-slave pairs across several interconnect providers.

Interconnect consumers are the entities which make use of the data paths exposed by the providers. The consumers send requests to providers requesting various throughput, latency and priority. Usually the consumers are device drivers, that send request based on their needs. An example for a consumer is a video decoder that supports various formats and image sizes.

<a id="rst-interconnect-providers"></a>

## Interconnect providers

Interconnect provider is an entity that implements methods to initialize and configure interconnect bus hardware. The interconnect provider drivers should be registered with the interconnect provider core.


#### <a id="c-struct-icc_node_data"></a>`struct icc_node_data`

icc node data

**Definition**

```c
struct icc_node_data {
    struct icc_node *node;
    u32 tag;
};
```

**Members**

- `node`: icc node
- `tag`: tag

#### <a id="c-struct-icc_onecell_data"></a>`struct icc_onecell_data`

driver data for onecell interconnect providers

**Definition**

```c
struct icc_onecell_data {
    unsigned int num_nodes;
    struct icc_node *nodes[] ;
};
```

**Members**

- `num_nodes`: number of nodes in this device
- `nodes`: array of pointers to the nodes in this device

#### <a id="c-struct-icc_provider"></a>`struct icc_provider`

interconnect provider (controller) entity that might provide multiple interconnect controls

**Definition**

```c
struct icc_provider {
    struct list_head        provider_list;
    struct list_head        nodes;
    int (*set)(struct icc_node *src, struct icc_node *dst);
    int (*aggregate)(struct icc_node *node, u32 tag, u32 avg_bw, u32 peak_bw, u32 *agg_avg, u32 *agg_peak);
    void (*pre_aggregate)(struct icc_node *node);
    int (*get_bw)(struct icc_node *node, u32 *avg, u32 *peak);
    struct icc_node* (*xlate)(const struct of_phandle_args *spec, void *data);
    struct icc_node_data* (*xlate_extended)(const struct of_phandle_args *spec, void *data);
    struct device           *dev;
    int users;
    bool inter_set;
    void *data;
};
```

**Members**

- `provider_list`: list of the registered interconnect providers
- `nodes`: internal list of the interconnect provider nodes
- `set`: pointer to device specific set operation function
- `aggregate`: pointer to device specific aggregate operation function
- `pre_aggregate`: pointer to device specific function that is called
  before the aggregation begins (optional)
- `get_bw`: pointer to device specific function to get current bandwidth
- `xlate`: provider-specific callback for mapping nodes from phandle arguments
- `xlate_extended`: vendor-specific callback for mapping node data from phandle arguments
- `dev`: the device this interconnect provider belongs to
- `users`: count of active users
- `inter_set`: whether inter-provider pairs will be configured with **set**
- `data`: pointer to private data

#### <a id="c-struct-icc_node"></a>`struct icc_node`

entity that is part of the interconnect topology

**Definition**

```c
struct icc_node {
    int id;
    const char              *name;
    struct icc_node         **links;
    size_t num_links;
    struct icc_provider     *provider;
    struct list_head        node_list;
    struct list_head        search_list;
    struct icc_node         *reverse;
    u8 is_traversed:1;
    struct hlist_head       req_list;
    u32 avg_bw;
    u32 peak_bw;
    u32 init_avg;
    u32 init_peak;
    void *data;
};
```

**Members**

- `id`: platform specific node id
- `name`: node name used in debugfs
- `links`: a list of targets pointing to where we can go next when traversing
- `num_links`: number of links to other interconnect nodes
- `provider`: points to the interconnect provider of this node
- `node_list`: the list entry in the parent provider's "nodes" list
- `search_list`: list used when walking the nodes graph
- `reverse`: pointer to previous node when walking the nodes graph
- `is_traversed`: flag that is used when walking the nodes graph
- `req_list`: a list of QoS constraint requests associated with this node
- `avg_bw`: aggregated value of average bandwidth requests from all consumers
- `peak_bw`: aggregated value of peak bandwidth requests from all consumers
- `init_avg`: average bandwidth value that is read from the hardware during init
- `init_peak`: peak bandwidth value that is read from the hardware during init
- `data`: pointer to private data


<a id="rst-interconnect-consumers"></a>

## Interconnect consumers

Interconnect consumers are the clients which use the interconnect APIs to get paths between endpoints and set their bandwidth/latency/QoS requirements for these interconnect paths.  These interfaces are not currently documented.

<a id="rst-interconnect-debugfs-interfaces"></a>

## Interconnect debugfs interfaces

Like several other subsystems interconnect will create some files for debugging and introspection. Files in debugfs are not considered ABI so application software shouldn't rely on format details change between kernel versions.

`/sys/kernel/debug/interconnect/interconnect_summary`:

Show all interconnect nodes in the system with their aggregated bandwidth request. Indented under each node show bandwidth requests from each device.

`/sys/kernel/debug/interconnect/interconnect_graph`:

Show the interconnect graph in the graphviz dot format. It shows all interconnect nodes and links in the system and groups together nodes from the same provider as subgraphs. The format is human-readable and can also be piped through dot to generate diagrams in many graphical formats:



```text
$ cat /sys/kernel/debug/interconnect/interconnect_graph | \
        dot -Tsvg > interconnect_graph.svg
```

The `test-client` directory provides interfaces for issuing BW requests to any arbitrary path. Note that for safety reasons, this feature is disabled by default without a Kconfig to enable it. Enabling it requires code changes to `#define INTERCONNECT_ALLOW_WRITE_DEBUGFS`. Example usage:



```text
cd /sys/kernel/debug/interconnect/test-client/

# Configure node endpoints for the path from CPU to DDR on
# qcom/sm8550.
echo chm_apps > src_node
echo ebi > dst_node

# Get path between src_node and dst_node. This is only
# necessary after updating the node endpoints.
echo 1 > get

# Set desired BW to 1GBps avg and 2GBps peak.
echo 1000000 > avg_bw
echo 2000000 > peak_bw

# Vote for avg_bw and peak_bw on the latest path from "get".
# Voting for multiple paths is possible by repeating this
# process for different nodes endpoints.
echo 1 > commit
```

---

# IPMB Driver for a Satellite MC

_Peios Kernel / Hardware and drivers / Driver development / Clocks, signals and platform services_

> The Intelligent Platform Management Bus or IPMB, is an I2C bus that provides a standardized interconnection between different boards within a chassis. This interconnection is between the baseboard management (BMC) and chassis electronics.…

<a id="rst-ipmb-driver-for-a-satellite-mc"></a>

The Intelligent Platform Management Bus or IPMB, is an I2C bus that provides a standardized interconnection between different boards within a chassis. This interconnection is between the baseboard management (BMC) and chassis electronics. IPMB is also associated with the messaging protocol through the IPMB bus.

The devices using the IPMB are usually management controllers that perform management functions such as servicing the front panel interface, monitoring the baseboard, hot-swapping disk drivers in the system chassis, etc...

When an IPMB is implemented in the system, the BMC serves as a controller to give system software access to the IPMB. The BMC sends IPMI requests to a device (usually a Satellite Management Controller or Satellite MC) via IPMB and the device sends a response back to the BMC.

For more information on IPMB and the format of an IPMB message, refer to the IPMB and IPMI specifications.

<a id="rst-ipmb-driver-for-satellite-mc"></a>

## IPMB driver for Satellite MC

ipmb-dev-int - This is the driver needed on a Satellite MC to receive IPMB messages from a BMC and send a response back. This driver works with the I2C driver and a userspace program such as OpenIPMI:

1. It is an I2C slave backend driver. So, it defines a callback function to set the Satellite MC as an I2C slave. This callback function handles the received IPMI requests.

2. It defines the read and write functions to enable a user space program (such as OpenIPMI) to communicate with the kernel.

<a id="rst-load-the-ipmb-driver"></a>

## Load the IPMB driver

The driver needs to be loaded at boot time or manually first. First, make sure you have the following in your config file: CONFIG_IPMB_DEVICE_INTERFACE=y

1. If you want the driver to be loaded at boot time:

- **a)** Add this entry to your ACPI table, under the appropriate SMBus:



  ```text
  Device (SMB0) // Example SMBus host controller
  {
  Name (_HID, "<Vendor-Specific HID>") // Vendor-Specific HID
  Name (_UID, 0) // Unique ID of particular host controller
  :
  :
    Device (IPMB)
    {
      Name (_HID, "IPMB0001") // IPMB device interface
      Name (_UID, 0) // Unique device identifier
    }
  }
  ```

- **b)** Example for device tree:



  ```text
  &i2c2 {
         status = "okay";

         ipmb@10 {
                 compatible = "ipmb-dev";
                 reg = <0x10>;
                 i2c-protocol;
         };
  };
  ```

If xmit of data to be done using raw i2c block vs smbus then "i2c-protocol" needs to be defined as above.

2. Manually from Linux:



   ```text
   modprobe ipmb-dev-int
   ```

<a id="rst-instantiate-the-device"></a>

## Instantiate the device

After loading the driver, you can instantiate the device as described in '[Documentation/i2c/instantiating-devices.rst](/kernel/hardware/i2c/instantiating-devices.md)'. If you have multiple BMCs, each connected to your Satellite MC via a different I2C bus, you can instantiate a device for each of those BMCs.

The name of the instantiated device contains the I2C bus number associated with it as follows:



```text
BMC1 ------ IPMB/I2C bus 1 ---------|   /dev/ipmb-1
                              Satellite MC
BMC1 ------ IPMB/I2C bus 2 ---------|   /dev/ipmb-2
```

For instance, you can instantiate the ipmb-dev-int device from user space at the 7 bit address 0x10 on bus 2:



```text
# echo ipmb-dev 0x1010 > /sys/bus/i2c/devices/i2c-2/new_device
```

This will create the device file /dev/ipmb-2, which can be accessed by the user space program. The device needs to be instantiated before running the user space program.

---

# The Linux IPMI Driver

_Peios Kernel / Hardware and drivers / Driver development / Clocks, signals and platform services_

> The Intelligent Platform Management Interface, or IPMI, is a standard for controlling intelligent devices that monitor a system. It provides for dynamic discovery of sensors in the system and the ability to monitor the sensors and be…

<a id="rst-the-linux-ipmi-driver"></a>

**Author:** Corey Minyard &lt;[minyard@mvista.com](<mailto:minyard@mvista.com>)&gt; / &lt;[minyard@acm.org](<mailto:minyard@acm.org>)&gt;

The Intelligent Platform Management Interface, or IPMI, is a standard for controlling intelligent devices that monitor a system. It provides for dynamic discovery of sensors in the system and the ability to monitor the sensors and be informed when the sensor's values change or go outside certain boundaries.  It also has a standardized database for field-replaceable units (FRUs) and a watchdog timer.

To use this, you need an interface to an IPMI controller in your system (called a Baseboard Management Controller, or BMC) and management software that can use the IPMI system.

This document describes how to use the IPMI driver for Linux.  If you are not familiar with IPMI itself, see the web site at [https://www.intel.com/design/servers/ipmi/index.htm](<https://www.intel.com/design/servers/ipmi/index.htm>).  IPMI is a big subject and I can't cover it all here\!

<a id="rst-configuration"></a>

## Configuration

The Linux IPMI driver is modular, which means you have to pick several things to have it work right depending on your hardware.  Most of these are available in the 'Character Devices' menu then the IPMI menu.

No matter what, you must pick 'IPMI top-level message handler' to use IPMI.  What you do beyond that depends on your needs and hardware.

The message handler does not provide any user-level interfaces. Kernel code (like the watchdog) can still use it.  If you need access from userland, you need to select 'Device interface for IPMI' if you want access through a device driver.

The driver interface depends on your hardware.  If your system properly provides the SMBIOS info for IPMI, the driver will detect it and just work.  If you have a board with a standard interface (These will generally be either "KCS", "SMIC", or "BT", consult your hardware manual), choose the 'IPMI SI handler' option.  A driver also exists for direct I2C access to the IPMI management controller.  Some boards support this, but it is unknown if it will work on every board.  For this, choose 'IPMI SMBus handler', but be ready to try to do some figuring to see if it will work on your system if the SMBIOS/ACPI information is wrong or not present.  It is fairly safe to have both these enabled and let the drivers auto-detect what is present.

You should generally enable ACPI on your system, as systems with IPMI can have ACPI tables describing them.

If you have a standard interface and the board manufacturer has done their job correctly, the IPMI controller should be automatically detected (via ACPI or SMBIOS tables) and should just work.  Sadly, many boards do not have this information.  The driver attempts standard defaults, but they may not work.  If you fall into this situation, you need to read the section below named 'The SI Driver' or "The SMBus Driver" on how to hand-configure your system.

IPMI defines a standard watchdog timer.  You can enable this with the 'IPMI Watchdog Timer' config option.  If you compile the driver into the kernel, then via a kernel command-line option you can have the watchdog timer start as soon as it initializes.  It also has a lot of other options, see the 'Watchdog' section below for more details. Note that you can also have the watchdog continue to run if it is closed (by default it is disabled on close).  Go into the 'Watchdog Cards' menu, enable 'Watchdog Timer Support', and enable the option 'Disable watchdog shutdown on close'.

IPMI systems can often be powered off using IPMI commands.  Select 'IPMI Poweroff' to do this.  The driver will auto-detect if the system can be powered off by IPMI.  It is safe to enable this even if your system doesn't support this option.  This works on ATCA systems, the Radisys CPI1 card, and any IPMI system that supports standard chassis management commands.

If you want the driver to put an event into the event log on a panic, enable the 'Generate a panic event to all BMCs on a panic' option.  If you want the whole panic string put into the event log using OEM events, enable the 'Generate OEM events containing the panic string' option.  You can also enable these dynamically by setting the module parameter named "panic_op" in the ipmi_msghandler module to "event" or "string".  Setting that parameter to "none" disables this function.

<a id="rst-basic-design"></a>

## Basic Design

The Linux IPMI driver is designed to be very modular and flexible, you only need to take the pieces you need and you can use it in many different ways.  Because of that, it's broken into many chunks of code.  These chunks (by module name) are:

ipmi_msghandler - This is the central piece of software for the IPMI system.  It handles all messages, message timing, and responses.  The IPMI users tie into this, and the IPMI physical interfaces (called System Management Interfaces, or SMIs) also tie in here.  This provides the kernelland interface for IPMI, but does not provide an interface for use by application processes.

ipmi_devintf - This provides a userland IOCTL interface for the IPMI driver, each open file for this device ties in to the message handler as an IPMI user.

ipmi_si - A driver for various system interfaces.  This supports KCS, SMIC, and BT interfaces.  Unless you have an SMBus interface or your own custom interface, you probably need to use this.

ipmi_ssif - A driver for accessing BMCs on the SMBus. It uses the I2C kernel driver's SMBus interfaces to send and receive IPMI messages over the SMBus.

ipmi_powernv - A driver for access BMCs on POWERNV systems.

ipmi_watchdog - IPMI requires systems to have a very capable watchdog timer.  This driver implements the standard Linux watchdog timer interface on top of the IPMI message handler.

ipmi_poweroff - Some systems support the ability to be turned off via IPMI commands.

bt-bmc - This is not part of the main driver, but instead a driver for accessing a BMC-side interface of a BT interface.  It is used on BMCs running Linux to provide an interface to the host.

These are all individually selectable via configuration options.

Much documentation for the interface is in the include files.  The IPMI include files are:

linux/ipmi.h - Contains the user interface and IOCTL interface for IPMI.

linux/ipmi_smi.h - Contains the interface for system management interfaces (things that interface to IPMI controllers) to use.

linux/ipmi_msgdefs.h - General definitions for base IPMI messaging.

<a id="rst-addressing"></a>

## Addressing

The IPMI addressing works much like IP addresses, you have an overlay to handle the different address types.  The overlay is:



```text
struct ipmi_addr
{
      int   addr_type;
      short channel;
      char  data[IPMI_MAX_ADDR_SIZE];
};
```

The addr_type determines what the address really is.  The driver currently understands two different types of addresses.

"System Interface" addresses are defined as:



```text
struct ipmi_system_interface_addr
{
      int   addr_type;
      short channel;
};
```

and the type is IPMI_SYSTEM_INTERFACE_ADDR_TYPE.  This is used for talking straight to the BMC on the current card.  The channel must be IPMI_BMC_CHANNEL.

Messages that are destined to go out on the IPMB bus going through the BMC use the IPMI_IPMB_ADDR_TYPE address type.  The format is:



```text
struct ipmi_ipmb_addr
{
      int           addr_type;
      short         channel;
      unsigned char slave_addr;
      unsigned char lun;
};
```

The "channel" here is generally zero, but some devices support more than one channel, it corresponds to the channel as defined in the IPMI spec.

There is also an IPMB direct address for a situation where the sender is directly on an IPMB bus and doesn't have to go through the BMC. You can send messages to a specific management controller (MC) on the IPMB using the IPMI_IPMB_DIRECT_ADDR_TYPE with the following format:



```text
struct ipmi_ipmb_direct_addr
{
      int           addr_type;
      short         channel;
      unsigned char slave_addr;
      unsigned char rq_lun;
      unsigned char rs_lun;
};
```

The channel is always zero.  You can also receive commands from other MCs that you have registered to handle and respond to them, so you can use this to implement a management controller on a bus..

<a id="rst-messages"></a>

## Messages

Messages are defined as:



```text
struct ipmi_msg
{
      unsigned char netfn;
      unsigned char lun;
      unsigned char cmd;
      unsigned char *data;
      int           data_len;
};
```

The driver takes care of adding/stripping the header information.  The data portion is just the data to be send (do NOT put addressing info here) or the response.  Note that the completion code of a response is the first item in "data", it is not stripped out because that is how all the messages are defined in the spec (and thus makes counting the offsets a little easier :-).

When using the IOCTL interface from userland, you must provide a block of data for "data", fill it, and set data_len to the length of the block of data, even when receiving messages.  Otherwise the driver will have no place to put the message.

Messages coming up from the message handler in kernelland will come in as:



```text
struct ipmi_recv_msg
{
      struct list_head link;

      /* The type of message as defined in the "Receive Types"
         defines above. */
      int         recv_type;

      ipmi_user_t      *user;
      struct ipmi_addr addr;
      long             msgid;
      struct ipmi_msg  msg;

      /* Call this when done with the message.  It will presumably free
         the message and do any other necessary cleanup. */
      void (*done)(struct ipmi_recv_msg *msg);

      /* Place-holder for the data, don't make any assumptions about
         the size or existence of this, since it may change. */
      unsigned char   msg_data[IPMI_MAX_MSG_LENGTH];
};
```

You should look at the receive type and handle the message appropriately.

<a id="rst-the-upper-layer-interface-message-handler"></a>

## The Upper Layer Interface (Message Handler)

The upper layer of the interface provides the users with a consistent view of the IPMI interfaces.  It allows multiple SMI interfaces to be addressed (because some boards actually have multiple BMCs on them) and the user should not have to care what type of SMI is below them.

<a id="rst-watching-for-interfaces"></a>

### Watching For Interfaces

When your code comes up, the IPMI driver may or may not have detected if IPMI devices exist.  So you might have to defer your setup until the device is detected, or you might be able to do it immediately. To handle this, and to allow for discovery, you register an SMI watcher with ipmi_smi_watcher_register() to iterate over interfaces and tell you when they come and go.

<a id="rst-creating-the-user"></a>

### Creating the User

To use the message handler, you must first create a user using ipmi_create_user.  The interface number specifies which SMI you want to connect to, and you must supply callback functions to be called when data comes in.  This also allows to you pass in a piece of data, the handler_data, that will be passed back to you on all calls.

Once you are done, call ipmi_destroy_user() to get rid of the user.

From userland, opening the device automatically creates a user, and closing the device automatically destroys the user.

<a id="rst-messaging"></a>

### Messaging

To send a message from kernel-land, the ipmi_request_settime() call does pretty much all message handling.  Most of the parameter are self-explanatory.  However, it takes a "msgid" parameter.  This is NOT the sequence number of messages.  It is simply a long value that is passed back when the response for the message is returned.  You may use it for anything you like.

Responses come back in the function pointed to by the ipmi_recv_hndl field of the "handler" that you passed in to ipmi_create_user(). Remember to look at the receive type, too.

From userland, you fill out an ipmi_req_t structure and use the IPMICTL_SEND_COMMAND ioctl.  For incoming stuff, you can use select() or poll() to wait for messages to come in.  However, you cannot use read() to get them, you must call the IPMICTL_RECEIVE_MSG with the ipmi_recv_t structure to actually get the message.  Remember that you must supply a pointer to a block of data in the msg.data field, and you must fill in the msg.data_len field with the size of the data. This gives the receiver a place to actually put the message.

If the message cannot fit into the data you provide, you will get an EMSGSIZE error and the driver will leave the data in the receive queue.  If you want to get it and have it truncate the message, use the IPMICTL_RECEIVE_MSG_TRUNC ioctl.

When you send a command (which is defined by the lowest-order bit of the netfn per the IPMI spec) on the IPMB bus, the driver will automatically assign the sequence number to the command and save the command.  If the response is not received in the IPMI-specified 5 seconds, it will generate a response automatically saying the command timed out.  If an unsolicited response comes in (if it was after 5 seconds, for instance), that response will be ignored.

In kernelland, after you receive a message and are done with it, you MUST call ipmi_free_recv_msg() on it, or you will leak messages.  Note that you should NEVER mess with the "done" field of a message, that is required to properly clean up the message.

Note that when sending, there is an ipmi_request_supply_msgs() call that lets you supply the smi and receive message.  This is useful for pieces of code that need to work even if the system is out of buffers (the watchdog timer uses this, for instance).  You supply your own buffer and own free routines.  This is not recommended for normal use, though, since it is tricky to manage your own buffers.

<a id="rst-events-and-incoming-commands"></a>

### Events and Incoming Commands

The driver takes care of polling for IPMI events and receiving commands (commands are messages that are not responses, they are commands that other things on the IPMB bus have sent you).  To receive these, you must register for them, they will not automatically be sent to you.

To receive events, you must call ipmi_set_gets_events() and set the "val" to non-zero.  Any events that have been received by the driver since startup will immediately be delivered to the first user that registers for events.  After that, if multiple users are registered for events, they will all receive all events that come in.

For receiving commands, you have to individually register commands you want to receive.  Call ipmi_register_for_cmd() and supply the netfn and command name for each command you want to receive.  You also specify a bitmask of the channels you want to receive the command from (or use IPMI_CHAN_ALL for all channels if you don't care).  Only one user may be registered for each netfn/cmd/channel, but different users may register for different commands, or the same command if the channel bitmasks do not overlap.

To respond to a received command, set the response bit in the returned netfn, use the address from the received message, and use the same msgid that you got in the received message.

From userland, equivalent IOCTLs are provided to do these functions.

<a id="rst-the-lower-layer-smi-interface"></a>

## The Lower Layer (SMI) Interface

As mentioned before, multiple SMI interfaces may be registered to the message handler, each of these is assigned an interface number when they register with the message handler.  They are generally assigned in the order they register, although if an SMI unregisters and then another one registers, all bets are off.

The ipmi_smi.h defines the interface for management interfaces, see that for more details.

<a id="rst-the-si-driver"></a>

## The SI Driver

The SI driver allows KCS, BT, and SMIC interfaces to be configured in the system.  It discovers interfaces through a host of different methods, depending on the system.

You can specify up to four interfaces on the module load line and control some module parameters:



```text
modprobe ipmi_si.o type=<type1>,<type2>....
     ports=<port1>,<port2>... addrs=<addr1>,<addr2>...
     irqs=<irq1>,<irq2>...
     regspacings=<sp1>,<sp2>,... regsizes=<size1>,<size2>,...
     regshifts=<shift1>,<shift2>,...
     slave_addrs=<addr1>,<addr2>,...
     force_kipmid=<enable1>,<enable2>,...
     kipmid_max_busy_us=<ustime1>,<ustime2>,...
     unload_when_empty=[0|1]
     trydmi=[0|1] tryacpi=[0|1]
     tryplatform=[0|1] trypci=[0|1]
```

Each of these except try... items is a list, the first item for the first interface, second item for the second interface, etc.

The si_type may be either "kcs", "smic", or "bt".  If you leave it blank, it defaults to "kcs".

If you specify addrs as non-zero for an interface, the driver will use the memory address given as the address of the device.  This overrides si_ports.

If you specify ports as non-zero for an interface, the driver will use the I/O port given as the device address.

If you specify irqs as non-zero for an interface, the driver will attempt to use the given interrupt for the device.

The other try... items disable discovery by their corresponding names.  These are all enabled by default, set them to zero to disable them.  The tryplatform disables openfirmware.

The next three parameters have to do with register layout.  The registers used by the interfaces may not appear at successive locations and they may not be in 8-bit registers.  These parameters allow the layout of the data in the registers to be more precisely specified.

The regspacings parameter give the number of bytes between successive register start addresses.  For instance, if the regspacing is set to 4 and the start address is 0xca2, then the address for the second register would be 0xca6.  This defaults to 1.

The regsizes parameter gives the size of a register, in bytes.  The data used by IPMI is 8-bits wide, but it may be inside a larger register.  This parameter allows the read and write type to be specified. It may be 1, 2, 4, or 8.  The default is 1.

Since the register size may be larger than 32 bits, the IPMI data may not be in the lower 8 bits.  The regshifts parameter give the amount to shift the data to get to the actual IPMI data.

The slave_addrs specifies the IPMI address of the local BMC.  This is usually 0x20 and the driver defaults to that, but in case it's not, it can be specified when the driver starts up.

The force_ipmid parameter forcefully enables (if set to 1) or disables (if set to 0) the kernel IPMI daemon.  Normally this is auto-detected by the driver, but systems with broken interrupts might need an enable, or users that don't want the daemon (don't need the performance, don't want the CPU hit) can disable it.

If unload_when_empty is set to 1, the driver will be unloaded if it doesn't find any interfaces or all the interfaces fail to work.  The default is one.  Setting to 0 is useful with the hotmod, but is obviously only useful for modules.

When compiled into the kernel, the parameters can be specified on the kernel command line as:



```text
ipmi_si.type=<type1>,<type2>...
     ipmi_si.ports=<port1>,<port2>... ipmi_si.addrs=<addr1>,<addr2>...
     ipmi_si.irqs=<irq1>,<irq2>...
     ipmi_si.regspacings=<sp1>,<sp2>,...
     ipmi_si.regsizes=<size1>,<size2>,...
     ipmi_si.regshifts=<shift1>,<shift2>,...
     ipmi_si.slave_addrs=<addr1>,<addr2>,...
     ipmi_si.force_kipmid=<enable1>,<enable2>,...
     ipmi_si.kipmid_max_busy_us=<ustime1>,<ustime2>,...
```

It works the same as the module parameters of the same names.

If your IPMI interface does not support interrupts and is a KCS or SMIC interface, the IPMI driver will start a kernel thread for the interface to help speed things up.  This is a low-priority kernel thread that constantly polls the IPMI driver while an IPMI operation is in progress.  The force_kipmid module parameter will allow the user to force this thread on or off.  If you force it off and don't have interrupts, the driver will run VERY slowly.  Don't blame me, these interfaces suck.

Unfortunately, this thread can use a lot of CPU depending on the interface's performance.  This can waste a lot of CPU and cause various issues with detecting idle CPU and using extra power.  To avoid this, the kipmid_max_busy_us sets the maximum amount of time, in microseconds, that kipmid will spin before sleeping for a tick.  This value sets a balance between performance and CPU waste and needs to be tuned to your needs.  Maybe, someday, auto-tuning will be added, but that's not a simple thing and even the auto-tuning would need to be tuned to the user's desired performance.

The driver supports a hot add and remove of interfaces.  This way, interfaces can be added or removed after the kernel is up and running. This is done using /sys/modules/ipmi_si/parameters/hotmod, which is a write-only parameter.  You write a string to this interface.  The string has the format:



```text
<op1>[:op2[:op3...]]
```

The "op"s are:



```text
add|remove,kcs|bt|smic,mem|i/o,<address>[,<opt1>[,<opt2>[,...]]]
```

You can specify more than one interface on the line.  The "opt"s are:



```text
rsp=<regspacing>
rsi=<regsize>
rsh=<regshift>
irq=<irq>
ipmb=<ipmb slave addr>
```

and these have the same meanings as discussed above.  Note that you can also use this on the kernel command line for a more compact format for specifying an interface.  Note that when removing an interface, only the first three parameters (si type, address type, and address) are used for the comparison.  Any options are ignored for removing.

<a id="rst-the-smbus-driver-ssif"></a>

## The SMBus Driver (SSIF)

The SMBus driver allows up to 4 SMBus devices to be configured in the system.  By default, the driver will only register with something it finds in DMI or ACPI tables.  You can change this at module load time (for a module) with:



```text
modprobe ipmi_ssif.o
      addr=<i2caddr1>[,<i2caddr2>[,...]]
      adapter=<adapter1>[,<adapter2>[...]]
      dbg=<flags1>,<flags2>...
      slave_addrs=<addr1>,<addr2>,...
      tryacpi=[0|1] trydmi=[0|1]
      [dbg_probe=1]
      alerts_broken
```

The addresses are normal I2C addresses.  The adapter is the string name of the adapter, as shown in /sys/bus/i2c/devices/i2c-&lt;n&gt;/name. It is *NOT* i2c-&lt;n&gt; itself.  Also, the comparison is done ignoring spaces, so if the name is "This is an I2C chip" you can say adapter_name=ThisisanI2cchip.  This is because it's hard to pass in spaces in kernel parameters.

The debug flags are bit flags for each BMC found, they are: IPMI messages: 1, driver state: 2, timing: 4, I2C probe: 8

The tryxxx parameters can be used to disable detecting interfaces from various sources.

Setting dbg_probe to 1 will enable debugging of the probing and detection process for BMCs on the SMBusses.

The slave_addrs specifies the IPMI address of the local BMC.  This is usually 0x20 and the driver defaults to that, but in case it's not, it can be specified when the driver starts up.

alerts_broken does not enable SMBus alert for SSIF. Otherwise SMBus alert will be enabled on supported hardware.

Discovering the IPMI compliant BMC on the SMBus can cause devices on the I2C bus to fail. The SMBus driver writes a "Get Device ID" IPMI message as a block write to the I2C bus and waits for a response. This action can be detrimental to some I2C devices. It is highly recommended that the known I2C address be given to the SMBus driver in the smb_addr parameter unless you have DMI or ACPI data to tell the driver what to use.

When compiled into the kernel, the addresses can be specified on the kernel command line as:



```text
ipmb_ssif.addr=<i2caddr1>[,<i2caddr2>[...]]
      ipmi_ssif.adapter=<adapter1>[,<adapter2>[...]]
      ipmi_ssif.dbg=<flags1>[,<flags2>[...]]
      ipmi_ssif.dbg_probe=1
      ipmi_ssif.slave_addrs=<addr1>[,<addr2>[...]]
      ipmi_ssif.tryacpi=[0|1] ipmi_ssif.trydmi=[0|1]
```

These are the same options as on the module command line.

The I2C driver does not support non-blocking access or polling, so this driver cannot do IPMI panic events, extend the watchdog at panic time, or other panic-related IPMI functions without special kernel patches and driver modifications.  You can get those at the openipmi web page.

The driver supports a hot add and remove of interfaces through the I2C sysfs interface.

<a id="rst-the-ipmi-ipmb-driver"></a>

## The IPMI IPMB Driver

This driver is for supporting a system that sits on an IPMB bus; it allows the interface to look like a normal IPMI interface.  Sending system interface addressed messages to it will cause the message to go to the registered BMC on the system (default at IPMI address 0x20).

It also allows you to directly address other MCs on the bus using the ipmb direct addressing.  You can receive commands from other MCs on the bus and they will be handled through the normal received command mechanism described above.

Parameters are:



```text
ipmi_ipmb.bmcaddr=<address to use for system interface addresses messages>
      ipmi_ipmb.retry_time_ms=<Time between retries on IPMB>
      ipmi_ipmb.max_retries=<Number of times to retry a message>
```

Loading the module will not result in the driver automatically starting unless there is device tree information setting it up.  If you want to instantiate one of these by hand, do:



```text
echo ipmi-ipmb <addr> > /sys/class/i2c-dev/i2c-<n>/device/new_device
```

Note that the address you give here is the I2C address, not the IPMI address.  So if you want your MC address to be 0x60, you put 0x30 here.  See the I2C driver info for more details.

Command bridging to other IPMB buses through this interface does not work.  The receive message queue is not implemented, by design.  There is only one receive message queue on a BMC, and that is meant for the host drivers, not something on the IPMB bus.

A BMC may have multiple IPMB buses, which bus your device sits on depends on how the system is wired.  You can fetch the channels with "ipmitool channel info &lt;n&gt;" where &lt;n&gt; is the channel, with the channels being 0-7 and try the IPMB channels.

<a id="rst-other-pieces"></a>

## Other Pieces

<a id="rst-get-the-detailed-info-related-with-the-ipmi-device"></a>

## Get the detailed info related with the IPMI device

Some users need more detailed information about a device, like where the address came from or the raw base device for the IPMI interface. You can use the IPMI smi_watcher to catch the IPMI interfaces as they come or go, and to grab the information, you can use the function ipmi_get_smi_info(), which returns the following structure:



```text
struct ipmi_smi_info {
      enum ipmi_addr_src addr_src;
      struct device *dev;
      union {
              struct {
                      void *acpi_handle;
              } acpi_info;
      } addr_info;
};
```

Currently special info for only for SI_ACPI address sources is returned.  Others may be added as necessary.

Note that the dev pointer is included in the above structure, and assuming ipmi_smi_get_info returns success, you must call put_device on the dev pointer.

<a id="rst-watchdog"></a>

## Watchdog

A watchdog timer is provided that implements the Linux-standard watchdog timer interface.  It has three module parameters that can be used to control it:



```text
modprobe ipmi_watchdog timeout=<t> pretimeout=<t> action=<action type>
    preaction=<preaction type> preop=<preop type> start_now=x
    nowayout=x ifnum_to_use=n panic_wdt_timeout=<t>
```

ifnum_to_use specifies which interface the watchdog timer should use. The default is -1, which means to pick the first one registered.

The timeout is the number of seconds to the action, and the pretimeout is the amount of seconds before the reset that the pre-timeout panic will occur (if pretimeout is zero, then pretimeout will not be enabled).  Note that the pretimeout is the time before the final timeout.  So if the timeout is 50 seconds and the pretimeout is 10 seconds, then the pretimeout will occur in 40 second (10 seconds before the timeout). The panic_wdt_timeout is the value of timeout which is set on kernel panic, in order to let actions such as kdump to occur during panic.

The action may be "reset", "power_cycle", or "power_off", and specifies what to do when the timer times out, and defaults to "reset".

The preaction may be "pre_smi" for an indication through the SMI interface, "pre_int" for an indication through the SMI with an interrupts, and "pre_nmi" for a NMI on a preaction.  This is how the driver is informed of the pretimeout.

The preop may be set to "preop_none" for no operation on a pretimeout, "preop_panic" to set the preoperation to panic, or "preop_give_data" to provide data to read from the watchdog device when the pretimeout occurs.  A "pre_nmi" setting CANNOT be used with "preop_give_data" because you can't do data operations from an NMI.

When preop is set to "preop_give_data", one byte comes ready to read on the device when the pretimeout occurs.  Select and fasync work on the device, as well.

If start_now is set to 1, the watchdog timer will start running as soon as the driver is loaded.

If nowayout is set to 1, the watchdog timer will not stop when the watchdog device is closed.  The default value of nowayout is true if the CONFIG_WATCHDOG_NOWAYOUT option is enabled, or false if not.

When compiled into the kernel, the kernel command line is available for configuring the watchdog:



```text
ipmi_watchdog.timeout=<t> ipmi_watchdog.pretimeout=<t>
      ipmi_watchdog.action=<action type>
      ipmi_watchdog.preaction=<preaction type>
      ipmi_watchdog.preop=<preop type>
      ipmi_watchdog.start_now=x
      ipmi_watchdog.nowayout=x
      ipmi_watchdog.panic_wdt_timeout=<t>
```

The options are the same as the module parameter options.

The watchdog will panic and start a 120 second reset timeout if it gets a pre-action.  During a panic or a reboot, the watchdog will start a 120 timer if it is running to make sure the reboot occurs.

Note that if you use the NMI preaction for the watchdog, you MUST NOT use the nmi watchdog.  There is no reasonable way to tell if an NMI comes from the IPMI controller, so it must assume that if it gets an otherwise unhandled NMI, it must be from IPMI and it will panic immediately.

Once you open the watchdog timer, you must write a 'V' character to the device to close it, or the timer will not stop.  This is a new semantic for the driver, but makes it consistent with the rest of the watchdog drivers in Linux.

<a id="rst-panic-timeouts"></a>

## Panic Timeouts

The OpenIPMI driver supports the ability to put semi-custom and custom events in the system event log if a panic occurs.  if you enable the 'Generate a panic event to all BMCs on a panic' option, you will get one event on a panic in a standard IPMI event format.  If you enable the 'Generate OEM events containing the panic string' option, you will also get a bunch of OEM events holding the panic string.

The field settings of the events are:

- Generator ID: 0x21 (kernel)

- EvM Rev: 0x03 (this event is formatting in IPMI 1.0 format)

- Sensor Type: 0x20 (OS critical stop sensor)

- Sensor \#: The first byte of the panic string (0 if no panic string)

- Event Dir \| Event Type: 0x6f (Assertion, sensor-specific event info)

- Event Data 1: 0xa1 (Runtime stop in OEM bytes 2 and 3)

- Event data 2: second byte of panic string

- Event data 3: third byte of panic string

See the IPMI spec for the details of the event layout.  This event is always sent to the local management controller.  It will handle routing the message to the right place

Other OEM events have the following format:

- Record ID (bytes 0-1): Set by the SEL.

- Record type (byte 2): 0xf0 (OEM non-timestamped)

- byte 3: The slave address of the card saving the panic

- byte 4: A sequence number (starting at zero) The rest of the bytes (11 bytes) are the panic string.  If the panic string is longer than 11 bytes, multiple messages will be sent with increasing sequence numbers.

Because you cannot send OEM events using the standard interface, this function will attempt to find an SEL and add the events there.  It will first query the capabilities of the local management controller. If it has an SEL, then they will be stored in the SEL of the local management controller.  If not, and the local management controller is an event generator, the event receiver from the local management controller will be queried and the events sent to the SEL on that device.  Otherwise, the events go nowhere since there is nowhere to send them.

<a id="rst-poweroff"></a>

## Poweroff

If the poweroff capability is selected, the IPMI driver will install a shutdown function into the standard poweroff function pointer.  This is in the ipmi_poweroff module.  When the system requests a powerdown, it will send the proper IPMI commands to do this.  This is supported on several platforms.

There is a module parameter named "poweroff_powercycle" that may either be zero (do a power down) or non-zero (do a power cycle, power the system off, then power it on in a few seconds).  Setting ipmi_poweroff.poweroff_control=x will do the same thing on the kernel command line.  The parameter is also available via the proc filesystem in /proc/sys/dev/ipmi/poweroff_powercycle.  Note that if the system does not support power cycling, it will always do the power off.

The "ifnum_to_use" parameter specifies which interface the poweroff code should use.  The default is -1, which means to pick the first one registered.

Note that if you have ACPI enabled, the system will prefer using ACPI to power off.

---

# The Common Mailbox Framework

_Peios Kernel / Hardware and drivers / Driver development / Clocks, signals and platform services_

> This document aims to help developers write client and controller drivers for the API. But before we start, let us note that the client (especially) and controller drivers are likely going to be very platform specific because the remote…

<a id="rst-the-common-mailbox-framework"></a>

**Author:** Jassi Brar &lt;[jaswinder.singh@linaro.org](<mailto:jaswinder.singh@linaro.org>)&gt;

This document aims to help developers write client and controller drivers for the API. But before we start, let us note that the client (especially) and controller drivers are likely going to be very platform specific because the remote firmware is likely to be proprietary and implement non-standard protocol. So even if two platforms employ, say, PL320 controller, the client drivers can't be shared across them. Even the PL320 driver might need to accommodate some platform specific quirks. So the API is meant mainly to avoid similar copies of code written for each platform. Having said that, nothing prevents the remote f/w to also be Linux based and use the same api there. However none of that helps us locally because we only ever deal at client's protocol level.

Some of the choices made during implementation are the result of this peculiarity of this "common" framework.

<a id="rst-controller-driver-see-include-linux-mailbox-controller-h"></a>

## Controller Driver (See include/linux/mailbox_controller.h)

Allocate mbox_controller and the array of mbox_chan. Populate mbox_chan_ops, except flush() and peek_data() all are mandatory. The controller driver might know a message has been consumed by the remote by getting an IRQ or polling some hardware flag or it can never know (the client knows by way of the protocol). The method in order of preference is IRQ -&gt; Poll -&gt; None, which the controller driver should set via 'txdone_irq' or 'txdone_poll' or neither.

<a id="rst-client-driver-see-include-linux-mailbox-client-h"></a>

## Client Driver (See include/linux/mailbox_client.h)

The client might want to operate in blocking mode (synchronously send a message through before returning) or non-blocking/async mode (submit a message and a callback function to the API and return immediately).



```text
struct demo_client {
        struct mbox_client cl;
        struct mbox_chan *mbox;
        struct completion c;
        bool async;
        /* ... */
};

/*
* This is the handler for data received from remote. The behaviour is purely
* dependent upon the protocol. This is just an example.
*/
static void message_from_remote(struct mbox_client *cl, void *mssg)
{
        struct demo_client *dc = container_of(cl, struct demo_client, cl);
        if (dc->async) {
                if (is_an_ack(mssg)) {
                        /* An ACK to our last sample sent */
                        return; /* Or do something else here */
                } else { /* A new message from remote */
                        queue_req(mssg);
                }
        } else {
                /* Remote f/w sends only ACK packets on this channel */
                return;
        }
}

static void sample_sent(struct mbox_client *cl, void *mssg, int r)
{
        struct demo_client *dc = container_of(cl, struct demo_client, cl);
        complete(&dc->c);
}

static void client_demo(struct platform_device *pdev)
{
        struct demo_client *dc_sync, *dc_async;
        /* The controller already knows async_pkt and sync_pkt */
        struct async_pkt ap;
        struct sync_pkt sp;

        dc_sync = kzalloc(sizeof(*dc_sync), GFP_KERNEL);
        dc_async = kzalloc(sizeof(*dc_async), GFP_KERNEL);

        /* Populate non-blocking mode client */
        dc_async->cl.dev = &pdev->dev;
        dc_async->cl.rx_callback = message_from_remote;
        dc_async->cl.tx_done = sample_sent;
        dc_async->cl.tx_block = false;
        dc_async->cl.tx_tout = 0; /* doesn't matter here */
        dc_async->cl.knows_txdone = false; /* depending upon protocol */
        dc_async->async = true;
        init_completion(&dc_async->c);

        /* Populate blocking mode client */
        dc_sync->cl.dev = &pdev->dev;
        dc_sync->cl.rx_callback = message_from_remote;
        dc_sync->cl.tx_done = NULL; /* operate in blocking mode */
        dc_sync->cl.tx_block = true;
        dc_sync->cl.tx_tout = 500; /* by half a second */
        dc_sync->cl.knows_txdone = false; /* depending upon protocol */
        dc_sync->async = false;

        /* ASync mailbox is listed second in 'mboxes' property */
        dc_async->mbox = mbox_request_channel(&dc_async->cl, 1);
        /* Populate data packet */
        /* ap.xxx = 123; etc */
        /* Send async message to remote */
        mbox_send_message(dc_async->mbox, &ap);

        /* Sync mailbox is listed first in 'mboxes' property */
        dc_sync->mbox = mbox_request_channel(&dc_sync->cl, 0);
        /* Populate data packet */
        /* sp.abc = 123; etc */
        /* Send message to remote in blocking mode */
        mbox_send_message(dc_sync->mbox, &sp);
        /* At this point 'sp' has been sent */

        /* Now wait for async chan to be done */
        wait_for_completion(&dc_async->c);
}
```

---

# NVMEM Subsystem

_Peios Kernel / Hardware and drivers / Driver development / Clocks, signals and platform services_

> Srinivas Kandagatla <srinivas.kandagatla@linaro.org>

<a id="rst-nvmem-subsystem"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

> Srinivas Kandagatla &lt;[srinivas.kandagatla@linaro.org](<mailto:srinivas.kandagatla@linaro.org>)&gt;

This document explains the NVMEM Framework along with the APIs provided, and how to use it.

<a id="rst-introduction"></a>

## 1. Introduction

*NVMEM* is the abbreviation for Non Volatile Memory layer. It is used to retrieve configuration of SOC or Device specific data from non volatile memories like eeprom, efuses and so on.

Before this framework existed, NVMEM drivers like eeprom were stored in drivers/misc, where they all had to duplicate pretty much the same code to register a sysfs file, allow in-kernel users to access the content of the devices they were driving, etc.

This was also a problem as far as other in-kernel users were involved, since the solutions used were pretty much different from one driver to another, there was a rather big abstraction leak.

This framework aims at solve these problems. It also introduces DT representation for consumer devices to go get the data they require (MAC Addresses, SoC/Revision ID, part numbers, and so on) from the NVMEMs.

<a id="rst-nvmem-providers"></a>

### NVMEM Providers

NVMEM provider refers to an entity that implements methods to initialize, read and write the non-volatile memory.

<a id="rst-registering-unregistering-the-nvmem-provider"></a>

## 2. Registering/Unregistering the NVMEM provider

A NVMEM provider can register with NVMEM core by supplying relevant nvmem configuration to nvmem_register(), on success core would return a valid nvmem_device pointer.

nvmem_unregister() is used to unregister a previously registered provider.

For example, a simple nvram case:



```text
static int brcm_nvram_probe(struct platform_device *pdev)
{
      struct nvmem_config config = {
              .name = "brcm-nvram",
              .reg_read = brcm_nvram_read,
      };
      ...
      config.dev = &pdev->dev;
      config.priv = priv;
      config.size = resource_size(res);

      devm_nvmem_register(&config);
}
```

Device drivers can define and register an nvmem cell using the nvmem_cell_info struct:



```text
static const struct nvmem_cell_info foo_nvmem_cell = {
      {
              .name           = "macaddr",
              .offset         = 0x7f00,
              .bytes          = ETH_ALEN,
      }
};

int nvmem_add_one_cell(nvmem, &foo_nvmem_cell);
```

Additionally it is possible to create nvmem cell lookup entries and register them with the nvmem framework from machine code as shown in the example below:



```text
static struct nvmem_cell_lookup foo_nvmem_lookup = {
      .nvmem_name             = "i2c-eeprom",
      .cell_name              = "macaddr",
      .dev_id                 = "foo_mac.0",
      .con_id                 = "mac-address",
};

nvmem_add_cell_lookups(&foo_nvmem_lookup, 1);
```

<a id="rst-nvmem-consumers"></a>

### NVMEM Consumers

NVMEM consumers are the entities which make use of the NVMEM provider to read from and to NVMEM.

<a id="rst-nvmem-cell-based-consumer-apis"></a>

## 3. NVMEM cell based consumer APIs

NVMEM cells are the data entries/fields in the NVMEM. The NVMEM framework provides 3 APIs to read/write NVMEM cells:



```text
struct nvmem_cell *nvmem_cell_get(struct device *dev, const char *name);
struct nvmem_cell *devm_nvmem_cell_get(struct device *dev, const char *name);

void nvmem_cell_put(struct nvmem_cell *cell);
void devm_nvmem_cell_put(struct device *dev, struct nvmem_cell *cell);

void *nvmem_cell_read(struct nvmem_cell *cell, ssize_t *len);
int nvmem_cell_write(struct nvmem_cell *cell, void *buf, ssize_t len);
```

`*nvmem_cell_get()` apis will get a reference to nvmem cell for a given id, and nvmem_cell_read/write() can then read or write to the cell. Once the usage of the cell is finished the consumer should call `*nvmem_cell_put()` to free all the allocation memory for the cell.

<a id="rst-direct-nvmem-device-based-consumer-apis"></a>

## 4. Direct NVMEM device based consumer APIs

In some instances it is necessary to directly read/write the NVMEM. To facilitate such consumers NVMEM framework provides below apis:



```text
struct nvmem_device *nvmem_device_get(struct device *dev, const char *name);
struct nvmem_device *devm_nvmem_device_get(struct device *dev,
                                         const char *name);
struct nvmem_device *nvmem_device_find(void *data,
                      int (*match)(struct device *dev, const void *data));
void nvmem_device_put(struct nvmem_device *nvmem);
int nvmem_device_read(struct nvmem_device *nvmem, unsigned int offset,
                    size_t bytes, void *buf);
int nvmem_device_write(struct nvmem_device *nvmem, unsigned int offset,
                     size_t bytes, void *buf);
int nvmem_device_cell_read(struct nvmem_device *nvmem,
                         struct nvmem_cell_info *info, void *buf);
int nvmem_device_cell_write(struct nvmem_device *nvmem,
                          struct nvmem_cell_info *info, void *buf);
```

Before the consumers can read/write NVMEM directly, it should get hold of nvmem_controller from one of the `*nvmem_device_get()` api.

The difference between these apis and cell based apis is that these apis always take nvmem_device as parameter.

<a id="rst-releasing-a-reference-to-the-nvmem"></a>

## 5. Releasing a reference to the NVMEM

When a consumer no longer needs the NVMEM, it has to release the reference to the NVMEM it has obtained using the APIs mentioned in the above section. The NVMEM framework provides 2 APIs to release a reference to the NVMEM:



```text
void nvmem_cell_put(struct nvmem_cell *cell);
void devm_nvmem_cell_put(struct device *dev, struct nvmem_cell *cell);
void nvmem_device_put(struct nvmem_device *nvmem);
void devm_nvmem_device_put(struct device *dev, struct nvmem_device *nvmem);
```

Both these APIs are used to release a reference to the NVMEM and devm_nvmem_cell_put and devm_nvmem_device_put destroys the devres associated with this NVMEM.

<a id="rst-userspace"></a>

### Userspace

<a id="rst-userspace-binary-interface"></a>

## 6. Userspace binary interface

Userspace can read/write the raw NVMEM file located at:



```text
/sys/bus/nvmem/devices/*/nvmem
```

ex:



```text
hexdump /sys/bus/nvmem/devices/qfprom0/nvmem

0000000 0000 0000 0000 0000 0000 0000 0000 0000
*
00000a0 db10 2240 0000 e000 0c00 0c00 0000 0c00
0000000 0000 0000 0000 0000 0000 0000 0000 0000
...
*
0001000
```

<a id="rst-devicetree-binding"></a>

## 7. DeviceTree Binding

See [Documentation/devicetree/bindings/nvmem/nvmem.txt](/kernel/hardware/devicetree/bindings-nvmem/nvmem.md)

<a id="rst-nvmem-layouts"></a>

## 8. NVMEM layouts

NVMEM layouts are yet another mechanism to create cells. With the device tree binding it is possible to specify simple cells by using an offset and a length. Sometimes, the cells doesn't have a static offset, but the content is still well defined, e.g. tag-length-values. In this case, the NVMEM device content has to be first parsed and the cells need to be added accordingly. Layouts let you read the content of the NVMEM device and let you add cells dynamically.

Another use case for layouts is the post processing of cells. With layouts, it is possible to associate a custom post processing hook to a cell. It even possible to add this hook to cells not created by the layout itself.

<a id="rst-internal-kernel-api"></a>

## 9. Internal kernel API


#### <a id="c-nvmem_add_one_cell"></a>`nvmem_add_one_cell()`

```c
int nvmem_add_one_cell(struct nvmem_device *nvmem, const struct nvmem_cell_info *info)
```

Add one cell information to an nvmem device

**Parameters**

- `struct nvmem_device *nvmem`: nvmem device to add cells to.
- `const struct nvmem_cell_info *info`: nvmem cell info to add to the device

**Return**

0 or negative error code on failure.

#### <a id="c-nvmem_register_notifier"></a>`nvmem_register_notifier()`

```c
int nvmem_register_notifier(struct notifier_block *nb)
```

Register a notifier block for nvmem events.

**Parameters**

- `struct notifier_block *nb`: notifier block to be called on nvmem events.

**Return**

0 on success, negative error number on failure.

#### <a id="c-nvmem_unregister_notifier"></a>`nvmem_unregister_notifier()`

```c
int nvmem_unregister_notifier(struct notifier_block *nb)
```

Unregister a notifier block for nvmem events.

**Parameters**

- `struct notifier_block *nb`: notifier block to be unregistered.

**Return**

0 on success, negative error number on failure.

#### <a id="c-nvmem_register"></a>`nvmem_register()`

```c
struct nvmem_device * nvmem_register(const struct nvmem_config *config)
```

Register a nvmem device for given nvmem_config. Also creates a binary entry in /sys/bus/nvmem/devices/dev-name/nvmem

**Parameters**

- `const struct nvmem_config *config`: nvmem device configuration with which nvmem device is created.

**Return**

Will be an [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR) on error or a valid pointer to nvmem_device
on success.

#### <a id="c-nvmem_unregister"></a>`nvmem_unregister()`

```c
void nvmem_unregister(struct nvmem_device *nvmem)
```

Unregister previously registered nvmem device

**Parameters**

- `struct nvmem_device *nvmem`: Pointer to previously registered nvmem device.

#### <a id="c-devm_nvmem_register"></a>`devm_nvmem_register()`

```c
struct nvmem_device * devm_nvmem_register(struct device *dev, const struct nvmem_config *config)
```

Register a managed nvmem device for given nvmem_config. Also creates a binary entry in /sys/bus/nvmem/devices/dev-name/nvmem

**Parameters**

- `struct device *dev`: Device that uses the nvmem device.
- `const struct nvmem_config *config`: nvmem device configuration with which nvmem device is created.

**Return**

Will be an [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR) on error or a valid pointer to nvmem_device
on success.

#### <a id="c-of_nvmem_device_get"></a>`of_nvmem_device_get()`

```c
struct nvmem_device * of_nvmem_device_get(struct device_node *np, const char *id)
```

Get nvmem device from a given id

**Parameters**

- `struct device_node *np`: Device tree node that uses the nvmem device.
- `const char *id`: nvmem name from nvmem-names property.

**Return**

[`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR) on error or a valid pointer to a struct nvmem_device
on success.

#### <a id="c-nvmem_device_get"></a>`nvmem_device_get()`

```c
struct nvmem_device * nvmem_device_get(struct device *dev, const char *dev_name)
```

Get nvmem device from a given id

**Parameters**

- `struct device *dev`: Device that uses the nvmem device.
- `const char *dev_name`: name of the requested nvmem device.

**Return**

[`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR) on error or a valid pointer to a struct nvmem_device
on success.

#### <a id="c-nvmem_device_find"></a>`nvmem_device_find()`

```c
struct nvmem_device * nvmem_device_find(void *data, int (*match)(struct device *dev, const void *data))
```

Find nvmem device with matching function

**Parameters**

- `void *data`: Data to pass to match function
- `int (*match)(struct device *dev, const void *data)`: Callback function to check device

**Return**

[`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR) on error or a valid pointer to a struct nvmem_device
on success.

#### <a id="c-devm_nvmem_device_put"></a>`devm_nvmem_device_put()`

```c
void devm_nvmem_device_put(struct device *dev, struct nvmem_device *nvmem)
```

put already got nvmem device

**Parameters**

- `struct device *dev`: Device that uses the nvmem device.
- `struct nvmem_device *nvmem`: pointer to nvmem device allocated by [`devm_nvmem_cell_get()`](#c-devm_nvmem_cell_get),
  that needs to be released.

#### <a id="c-nvmem_device_put"></a>`nvmem_device_put()`

```c
void nvmem_device_put(struct nvmem_device *nvmem)
```

put already got nvmem device

**Parameters**

- `struct nvmem_device *nvmem`: pointer to nvmem device that needs to be released.

#### <a id="c-devm_nvmem_device_get"></a>`devm_nvmem_device_get()`

```c
struct nvmem_device * devm_nvmem_device_get(struct device *dev, const char *id)
```

Get nvmem device of device from a given id

**Parameters**

- `struct device *dev`: Device that requests the nvmem device.
- `const char *id`: name id for the requested nvmem device.

**Return**

[`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR) on error or a valid pointer to a struct nvmem_device
on success.  The nvmem_device will be freed by the automatically once the
device is freed.

#### <a id="c-of_nvmem_cell_get"></a>`of_nvmem_cell_get()`

```c
struct nvmem_cell * of_nvmem_cell_get(struct device_node *np, const char *id)
```

Get a nvmem cell from given device node and cell id

**Parameters**

- `struct device_node *np`: Device tree node that uses the nvmem cell.
- `const char *id`: nvmem cell name from nvmem-cell-names property, or NULL
  for the cell at index 0 (the lone cell with no accompanying
  nvmem-cell-names property).

**Return**

Will be an [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR) on error or a valid pointer
to a struct nvmem_cell.  The nvmem_cell will be freed by the
[`nvmem_cell_put()`](#c-nvmem_cell_put).

#### <a id="c-nvmem_cell_get"></a>`nvmem_cell_get()`

```c
struct nvmem_cell * nvmem_cell_get(struct device *dev, const char *id)
```

Get nvmem cell of device from a given cell name

**Parameters**

- `struct device *dev`: Device that requests the nvmem cell.
- `const char *id`: nvmem cell name to get (this corresponds with the name from the
  nvmem-cell-names property for DT systems and with the con_id from
  the lookup entry for non-DT systems).

**Return**

Will be an [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR) on error or a valid pointer
to a struct nvmem_cell.  The nvmem_cell will be freed by the
[`nvmem_cell_put()`](#c-nvmem_cell_put).

#### <a id="c-devm_nvmem_cell_get"></a>`devm_nvmem_cell_get()`

```c
struct nvmem_cell * devm_nvmem_cell_get(struct device *dev, const char *id)
```

Get nvmem cell of device from a given id

**Parameters**

- `struct device *dev`: Device that requests the nvmem cell.
- `const char *id`: nvmem cell name id to get.

**Return**

Will be an [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR) on error or a valid pointer
to a struct nvmem_cell.  The nvmem_cell will be freed by the
automatically once the device is freed.

#### <a id="c-devm_nvmem_cell_put"></a>`devm_nvmem_cell_put()`

```c
void devm_nvmem_cell_put(struct device *dev, struct nvmem_cell *cell)
```

Release previously allocated nvmem cell from devm_nvmem_cell_get.

**Parameters**

- `struct device *dev`: Device that requests the nvmem cell.
- `struct nvmem_cell *cell`: Previously allocated nvmem cell by [`devm_nvmem_cell_get()`](#c-devm_nvmem_cell_get).

#### <a id="c-nvmem_cell_put"></a>`nvmem_cell_put()`

```c
void nvmem_cell_put(struct nvmem_cell *cell)
```

Release previously allocated nvmem cell.

**Parameters**

- `struct nvmem_cell *cell`: Previously allocated nvmem cell by [`nvmem_cell_get()`](#c-nvmem_cell_get).

#### <a id="c-nvmem_cell_read"></a>`nvmem_cell_read()`

```c
void * nvmem_cell_read(struct nvmem_cell *cell, size_t *len)
```

Read a given nvmem cell

**Parameters**

- `struct nvmem_cell *cell`: nvmem cell to be read.
- `size_t *len`: pointer to length of cell which will be populated on successful read;
  can be NULL.

**Return**

[`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR) on error or a valid pointer to a buffer on success. The
buffer should be freed by the consumer with a [`kfree()`](/kernel/internals/core-api/mm-api.md#c-kfree).

#### <a id="c-nvmem_cell_write"></a>`nvmem_cell_write()`

```c
int nvmem_cell_write(struct nvmem_cell *cell, void *buf, size_t len)
```

Write to a given nvmem cell

**Parameters**

- `struct nvmem_cell *cell`: nvmem cell to be written.
- `void *buf`: Buffer to be written.
- `size_t len`: length of buffer to be written to nvmem cell.

**Return**

length of bytes written or negative on failure.

#### <a id="c-nvmem_cell_read_u8"></a>`nvmem_cell_read_u8()`

```c
int nvmem_cell_read_u8(struct device *dev, const char *cell_id, u8 *val)
```

Read a cell value as a u8

**Parameters**

- `struct device *dev`: Device that requests the nvmem cell.
- `const char *cell_id`: Name of nvmem cell to read.
- `u8 *val`: pointer to output value.

**Return**

0 on success or negative errno.

#### <a id="c-nvmem_cell_read_u16"></a>`nvmem_cell_read_u16()`

```c
int nvmem_cell_read_u16(struct device *dev, const char *cell_id, u16 *val)
```

Read a cell value as a u16

**Parameters**

- `struct device *dev`: Device that requests the nvmem cell.
- `const char *cell_id`: Name of nvmem cell to read.
- `u16 *val`: pointer to output value.

**Return**

0 on success or negative errno.

#### <a id="c-nvmem_cell_read_u32"></a>`nvmem_cell_read_u32()`

```c
int nvmem_cell_read_u32(struct device *dev, const char *cell_id, u32 *val)
```

Read a cell value as a u32

**Parameters**

- `struct device *dev`: Device that requests the nvmem cell.
- `const char *cell_id`: Name of nvmem cell to read.
- `u32 *val`: pointer to output value.

**Return**

0 on success or negative errno.

#### <a id="c-nvmem_cell_read_u64"></a>`nvmem_cell_read_u64()`

```c
int nvmem_cell_read_u64(struct device *dev, const char *cell_id, u64 *val)
```

Read a cell value as a u64

**Parameters**

- `struct device *dev`: Device that requests the nvmem cell.
- `const char *cell_id`: Name of nvmem cell to read.
- `u64 *val`: pointer to output value.

**Return**

0 on success or negative errno.

#### <a id="c-nvmem_cell_read_variable_le_u32"></a>`nvmem_cell_read_variable_le_u32()`

```c
int nvmem_cell_read_variable_le_u32(struct device *dev, const char *cell_id, u32 *val)
```

Read up to 32-bits of data as a little endian number.

**Parameters**

- `struct device *dev`: Device that requests the nvmem cell.
- `const char *cell_id`: Name of nvmem cell to read.
- `u32 *val`: pointer to output value.

**Return**

0 on success or negative errno.

#### <a id="c-nvmem_cell_read_variable_le_u64"></a>`nvmem_cell_read_variable_le_u64()`

```c
int nvmem_cell_read_variable_le_u64(struct device *dev, const char *cell_id, u64 *val)
```

Read up to 64-bits of data as a little endian number.

**Parameters**

- `struct device *dev`: Device that requests the nvmem cell.
- `const char *cell_id`: Name of nvmem cell to read.
- `u64 *val`: pointer to output value.

**Return**

0 on success or negative errno.

#### <a id="c-nvmem_device_cell_read"></a>`nvmem_device_cell_read()`

```c
ssize_t nvmem_device_cell_read(struct nvmem_device *nvmem, struct nvmem_cell_info *info, void *buf)
```

Read a given nvmem device and cell

**Parameters**

- `struct nvmem_device *nvmem`: nvmem device to read from.
- `struct nvmem_cell_info *info`: nvmem cell info to be read.
- `void *buf`: buffer pointer which will be populated on successful read.

**Return**

length of successful bytes read on success and negative
error code on error.

#### <a id="c-nvmem_device_cell_write"></a>`nvmem_device_cell_write()`

```c
int nvmem_device_cell_write(struct nvmem_device *nvmem, struct nvmem_cell_info *info, void *buf)
```

Write cell to a given nvmem device

**Parameters**

- `struct nvmem_device *nvmem`: nvmem device to be written to.
- `struct nvmem_cell_info *info`: nvmem cell info to be written.
- `void *buf`: buffer to be written to cell.

**Return**

length of bytes written or negative error code on failure.

#### <a id="c-nvmem_device_read"></a>`nvmem_device_read()`

```c
int nvmem_device_read(struct nvmem_device *nvmem, unsigned int offset, size_t bytes, void *buf)
```

Read from a given nvmem device

**Parameters**

- `struct nvmem_device *nvmem`: nvmem device to read from.
- `unsigned int offset`: offset in nvmem device.
- `size_t bytes`: number of bytes to read.
- `void *buf`: buffer pointer which will be populated on successful read.

**Return**

length of successful bytes read on success and negative
error code on error.

#### <a id="c-nvmem_device_write"></a>`nvmem_device_write()`

```c
int nvmem_device_write(struct nvmem_device *nvmem, unsigned int offset, size_t bytes, void *buf)
```

Write cell to a given nvmem device

**Parameters**

- `struct nvmem_device *nvmem`: nvmem device to be written to.
- `unsigned int offset`: offset in nvmem device.
- `size_t bytes`: number of bytes to write.
- `void *buf`: buffer to be written.

**Return**

length of bytes written or negative error code on failure.

#### <a id="c-nvmem_add_cell_lookups"></a>`nvmem_add_cell_lookups()`

```c
void nvmem_add_cell_lookups(struct nvmem_cell_lookup *entries, size_t nentries)
```

register a list of cell lookup entries

**Parameters**

- `struct nvmem_cell_lookup *entries`: array of cell lookup entries
- `size_t nentries`: number of cell lookup entries in the array

#### <a id="c-nvmem_del_cell_lookups"></a>`nvmem_del_cell_lookups()`

```c
void nvmem_del_cell_lookups(struct nvmem_cell_lookup *entries, size_t nentries)
```

remove a list of previously added cell lookup entries

**Parameters**

- `struct nvmem_cell_lookup *entries`: array of cell lookup entries
- `size_t nentries`: number of cell lookup entries in the array

#### <a id="c-nvmem_dev_name"></a>`nvmem_dev_name()`

```c
const char * nvmem_dev_name(struct nvmem_device *nvmem)
```

Get the name of a given nvmem device.

**Parameters**

- `struct nvmem_device *nvmem`: nvmem device.

**Return**

name of the nvmem device.

#### <a id="c-nvmem_dev_size"></a>`nvmem_dev_size()`

```c
size_t nvmem_dev_size(struct nvmem_device *nvmem)
```

Get the size of a given nvmem device.

**Parameters**

- `struct nvmem_device *nvmem`: nvmem device.

**Return**

size of the nvmem device.

---

# PINCTRL (PIN CONTROL) subsystem

_Peios Kernel / Hardware and drivers / Driver development / Clocks, signals and platform services_

> This document outlines the pin control subsystem in Linux

<a id="rst-pinctrl-pin-control-subsystem"></a>

This document outlines the pin control subsystem in Linux

This subsystem deals with:

- Enumerating and naming controllable pins

- Multiplexing of pins, pads, fingers (etc) see below for details

- Configuration of pins, pads, fingers (etc), such as software-controlled biasing and driving mode specific pins, such as pull-up, pull-down, open drain, load capacitance etc.

<a id="rst-top-level-interface"></a>

## Top-level interface

Definitions:

- A PIN CONTROLLER is a piece of hardware, usually a set of registers, that can control PINs. It may be able to multiplex, bias, set load capacitance, set drive strength, etc. for individual pins or groups of pins.

- PINS are equal to pads, fingers, balls or whatever packaging input or output line you want to control and these are denoted by unsigned integers in the range 0..maxpin. This numberspace is local to each PIN CONTROLLER, so there may be several such number spaces in a system. This pin space may be sparse - i.e. there may be gaps in the space with numbers where no pin exists.

When a PIN CONTROLLER is instantiated, it will register a descriptor to the pin control framework, and this descriptor contains an array of pin descriptors describing the pins handled by this specific pin controller.

Here is an example of a PGA (Pin Grid Array) chip seen from underneath:



```text
     A   B   C   D   E   F   G   H

8    o   o   o   o   o   o   o   o

7    o   o   o   o   o   o   o   o

6    o   o   o   o   o   o   o   o

5    o   o   o   o   o   o   o   o

4    o   o   o   o   o   o   o   o

3    o   o   o   o   o   o   o   o

2    o   o   o   o   o   o   o   o

1    o   o   o   o   o   o   o   o
```

To register a pin controller and name all the pins on this package we can do this in our driver:



```c
#include <linux/pinctrl/pinctrl.h>

const struct pinctrl_pin_desc foo_pins[] = {
        PINCTRL_PIN(0, "A8"),
        PINCTRL_PIN(1, "B8"),
        PINCTRL_PIN(2, "C8"),
        ...
        PINCTRL_PIN(61, "F1"),
        PINCTRL_PIN(62, "G1"),
        PINCTRL_PIN(63, "H1"),
};

static struct pinctrl_desc foo_desc = {
        .name = "foo",
        .pins = foo_pins,
        .npins = ARRAY_SIZE(foo_pins),
        .owner = THIS_MODULE,
};

int __init foo_init(void)
{
        int error;

        struct pinctrl_dev *pctl;

        error = pinctrl_register_and_init(&foo_desc, <PARENT>, NULL, &pctl);
        if (error)
                return error;

        return pinctrl_enable(pctl);
}
```

To enable the pinctrl subsystem and the subgroups for PINMUX and PINCONF and selected drivers, you need to select them from your machine's Kconfig entry, since these are so tightly integrated with the machines they are used on. See `arch/arm/mach-ux500/Kconfig` for an example.

Pins usually have fancier names than this. You can find these in the datasheet for your chip. Notice that the core pinctrl.h file provides a fancy macro called `PINCTRL_PIN()` to create the struct entries. As you can see the pins are enumerated from 0 in the upper left corner to 63 in the lower right corner. This enumeration was arbitrarily chosen, in practice you need to think through your numbering system so that it matches the layout of registers and such things in your driver, or the code may become complicated. You must also consider matching of offsets to the GPIO ranges that may be handled by the pin controller.

For a padding with 467 pads, as opposed to actual pins, the enumeration will be like this, walking around the edge of the chip, which seems to be industry standard too (all these pads had names, too):



```text
  0 ..... 104
466        105
  .        .
  .        .
358        224
 357 .... 225
```

<a id="rst-pin-groups"></a>

## Pin groups

Many controllers need to deal with groups of pins, so the pin controller subsystem has a mechanism for enumerating groups of pins and retrieving the actual enumerated pins that are part of a certain group.

For example, say that we have a group of pins dealing with an SPI interface on \{ 0, 8, 16, 24 \}, and a group of pins dealing with an I2C interface on pins on \{ 24, 25 \}.

These two groups are presented to the pin control subsystem by implementing some generic `pinctrl_ops` like this:



```c
#include <linux/pinctrl/pinctrl.h>

static const unsigned int spi0_pins[] = { 0, 8, 16, 24 };
static const unsigned int i2c0_pins[] = { 24, 25 };

static const struct pingroup foo_groups[] = {
        PINCTRL_PINGROUP("spi0_grp", spi0_pins, ARRAY_SIZE(spi0_pins)),
        PINCTRL_PINGROUP("i2c0_grp", i2c0_pins, ARRAY_SIZE(i2c0_pins)),
};

static int foo_get_groups_count(struct pinctrl_dev *pctldev)
{
        return ARRAY_SIZE(foo_groups);
}

static const char *foo_get_group_name(struct pinctrl_dev *pctldev,
                                      unsigned int selector)
{
        return foo_groups[selector].name;
}

static int foo_get_group_pins(struct pinctrl_dev *pctldev,
                              unsigned int selector,
                              const unsigned int **pins,
                              unsigned int *npins)
{
        *pins = foo_groups[selector].pins;
        *npins = foo_groups[selector].npins;
        return 0;
}

static struct pinctrl_ops foo_pctrl_ops = {
        .get_groups_count = foo_get_groups_count,
        .get_group_name = foo_get_group_name,
        .get_group_pins = foo_get_group_pins,
};

static struct pinctrl_desc foo_desc = {
        ...
        .pctlops = &foo_pctrl_ops,
};
```

The pin control subsystem will call the `.get_groups_count()` function to determine the total number of legal selectors, then it will call the other functions to retrieve the name and pins of the group. Maintaining the data structure of the groups is up to the driver, this is just a simple example - in practice you may need more entries in your group structure, for example specific register ranges associated with each group and so on.

<a id="rst-pin-configuration"></a>

## Pin configuration

Pins can sometimes be software-configured in various ways, mostly related to their electronic properties when used as inputs or outputs. For example you may be able to make an output pin high impedance (Hi-Z), or "tristate" meaning it is effectively disconnected. You may be able to connect an input pin to VDD or GND using a certain resistor value - pull up and pull down - so that the pin has a stable value when nothing is driving the rail it is connected to, or when it's unconnected.

Pin configuration can be programmed by adding configuration entries into the mapping table; see section [Board/machine configuration](<#rst-board-machine-configuration>) below.

The format and meaning of the configuration parameter, PLATFORM_X_PULL_UP above, is entirely defined by the pin controller driver.

The pin configuration driver implements callbacks for changing pin configuration in the pin controller ops like this:



```c
#include <linux/pinctrl/pinconf.h>
#include <linux/pinctrl/pinctrl.h>

#include "platform_x_pindefs.h"

static int foo_pin_config_get(struct pinctrl_dev *pctldev,
                              unsigned int offset,
                              unsigned long *config)
{
        struct my_conftype conf;

        /* ... Find setting for pin @ offset ... */

        *config = (unsigned long) conf;
}

static int foo_pin_config_set(struct pinctrl_dev *pctldev,
                              unsigned int offset,
                              unsigned long config)
{
        struct my_conftype *conf = (struct my_conftype *) config;

        switch (conf) {
                case PLATFORM_X_PULL_UP:
                ...
                break;
        }
}

static int foo_pin_config_group_get(struct pinctrl_dev *pctldev,
                                    unsigned selector,
                                    unsigned long *config)
{
        ...
}

static int foo_pin_config_group_set(struct pinctrl_dev *pctldev,
                                    unsigned selector,
                                    unsigned long config)
{
        ...
}

static struct pinconf_ops foo_pconf_ops = {
        .pin_config_get = foo_pin_config_get,
        .pin_config_set = foo_pin_config_set,
        .pin_config_group_get = foo_pin_config_group_get,
        .pin_config_group_set = foo_pin_config_group_set,
};

/* Pin config operations are handled by some pin controller */
static struct pinctrl_desc foo_desc = {
        ...
        .confops = &foo_pconf_ops,
};
```

<a id="rst-interaction-with-the-gpio-subsystem"></a>

## Interaction with the GPIO subsystem

The GPIO drivers may want to perform operations of various types on the same physical pins that are also registered as pin controller pins.

First and foremost, the two subsystems can be used as completely orthogonal, see the section named [Pin control requests from drivers](<#rst-pin-control-requests-from-drivers>) and [Drivers needing both pin control and GPIOs](<#rst-drivers-needing-both-pin-control-and-gpios>) below for details. But in some situations a cross-subsystem mapping between pins and GPIOs is needed.

Since the pin controller subsystem has its pinspace local to the pin controller we need a mapping so that the pin control subsystem can figure out which pin controller handles control of a certain GPIO pin. Since a single pin controller may be muxing several GPIO ranges (typically SoCs that have one set of pins, but internally several GPIO silicon blocks, each modelled as a struct gpio_chip) any number of GPIO ranges can be added to a pin controller instance like this:



```c
#include <linux/gpio/driver.h>

#include <linux/pinctrl/pinctrl.h>

struct gpio_chip chip_a;
struct gpio_chip chip_b;

static struct pinctrl_gpio_range gpio_range_a = {
        .name = "chip a",
        .id = 0,
        .base = 32,
        .pin_base = 32,
        .npins = 16,
        .gc = &chip_a,
};

static struct pinctrl_gpio_range gpio_range_b = {
        .name = "chip b",
        .id = 0,
        .base = 48,
        .pin_base = 64,
        .npins = 8,
        .gc = &chip_b;
};

int __init foo_init(void)
{
        struct pinctrl_dev *pctl;
        ...
        pinctrl_add_gpio_range(pctl, &gpio_range_a);
        pinctrl_add_gpio_range(pctl, &gpio_range_b);
        ...
}
```

So this complex system has one pin controller handling two different GPIO chips. "chip a" has 16 pins and "chip b" has 8 pins. The "chip a" and "chip b" have different `pin_base`, which means a start pin number of the GPIO range.

The GPIO range of "chip a" starts from the GPIO base of 32 and actual pin range also starts from 32. However "chip b" has different starting offset for the GPIO range and pin range. The GPIO range of "chip b" starts from GPIO number 48, while the pin range of "chip b" starts from 64.

We can convert a gpio number to actual pin number using this `pin_base`. They are mapped in the global GPIO pin space at:

- **chip a:**

  - GPIO range : \[32 .. 47\]

  - pin range  : \[32 .. 47\]

- **chip b:**

  - GPIO range : \[48 .. 55\]

  - pin range  : \[64 .. 71\]

The above examples assume the mapping between the GPIOs and pins is linear. If the mapping is sparse or haphazard, an array of arbitrary pin numbers can be encoded in the range like this:



```c
static const unsigned int range_pins[] = { 14, 1, 22, 17, 10, 8, 6, 2 };

static struct pinctrl_gpio_range gpio_range = {
        .name = "chip",
        .id = 0,
        .base = 32,
        .pins = &range_pins,
        .npins = ARRAY_SIZE(range_pins),
        .gc = &chip,
};
```

In this case the `pin_base` property will be ignored. If the name of a pin group is known, the pins and npins elements of the above structure can be initialised using the function `pinctrl_get_group_pins()`, e.g. for pin group "foo":



```c
pinctrl_get_group_pins(pctl, "foo", &gpio_range.pins, &gpio_range.npins);
```

When GPIO-specific functions in the pin control subsystem are called, these ranges will be used to look up the appropriate pin controller by inspecting and matching the pin to the pin ranges across all controllers. When a pin controller handling the matching range is found, GPIO-specific functions will be called on that specific pin controller.

For all functionalities dealing with pin biasing, pin muxing etc, the pin controller subsystem will look up the corresponding pin number from the passed in gpio number, and use the range's internals to retrieve a pin number. After that, the subsystem passes it on to the pin control driver, so the driver will get a pin number into its handled number range. Further it is also passed the range ID value, so that the pin controller knows which range it should deal with.

Calling `pinctrl_add_gpio_range()` from pinctrl driver is DEPRECATED. Please see section 2.1 of `Documentation/devicetree/bindings/gpio/gpio.txt` on how to bind pinctrl and gpio drivers.

<a id="rst-pinmux-interfaces"></a>

## PINMUX interfaces

These calls use the pinmux\_\* naming prefix.  No other calls should use that prefix.

<a id="rst-what-is-pinmuxing"></a>

## What is pinmuxing?

PINMUX, also known as padmux, ballmux, alternate functions or mission modes is a way for chip vendors producing some kind of electrical packages to use a certain physical pin (ball, pad, finger, etc) for multiple mutually exclusive functions, depending on the application. By "application" in this context we usually mean a way of soldering or wiring the package into an electronic system, even though the framework makes it possible to also change the function at runtime.

Here is an example of a PGA (Pin Grid Array) chip seen from underneath:



```text
     A   B   C   D   E   F   G   H
   +---+
8  | o | o   o   o   o   o   o   o
   |   |
7  | o | o   o   o   o   o   o   o
   |   |
6  | o | o   o   o   o   o   o   o
   +---+---+
5  | o | o | o   o   o   o   o   o
   +---+---+               +---+
4    o   o   o   o   o   o | o | o
                           |   |
3    o   o   o   o   o   o | o | o
                           |   |
2    o   o   o   o   o   o | o | o
   +-------+-------+-------+---+---+
1  | o   o | o   o | o   o | o | o |
   +-------+-------+-------+---+---+
```

This is not tetris. The game to think of is chess. Not all PGA/BGA packages are chessboard-like, big ones have "holes" in some arrangement according to different design patterns, but we're using this as a simple example. Of the pins you see some will be taken by things like a few VCC and GND to feed power to the chip, and quite a few will be taken by large ports like an external memory interface. The remaining pins will often be subject to pin multiplexing.

The example 8x8 PGA package above will have pin numbers 0 through 63 assigned to its physical pins. It will name the pins \{ A1, A2, A3 ... H6, H7, H8 \} using pinctrl_register_pins() and a suitable data set as shown earlier.

In this 8x8 BGA package the pins \{ A8, A7, A6, A5 \} can be used as an SPI port (these are four pins: CLK, RXD, TXD, FRM). In that case, pin B5 can be used as some general-purpose GPIO pin. However, in another setting, pins \{ A5, B5 \} can be used as an I2C port (these are just two pins: SCL, SDA). Needless to say, we cannot use the SPI port and I2C port at the same time. However in the inside of the package the silicon performing the SPI logic can alternatively be routed out on pins \{ G4, G3, G2, G1 \}.

On the bottom row at \{ A1, B1, C1, D1, E1, F1, G1, H1 \} we have something special - it's an external MMC bus that can be 2, 4 or 8 bits wide, and it will consume 2, 4 or 8 pins respectively, so either \{ A1, B1 \} are taken or \{ A1, B1, C1, D1 \} or all of them. If we use all 8 bits, we cannot use the SPI port on pins \{ G4, G3, G2, G1 \} of course.

This way the silicon blocks present inside the chip can be multiplexed "muxed" out on different pin ranges. Often contemporary SoC (systems on chip) will contain several I2C, SPI, SDIO/MMC, etc silicon blocks that can be routed to different pins by pinmux settings.

Since general-purpose I/O pins (GPIO) are typically always in shortage, it is common to be able to use almost any pin as a GPIO pin if it is not currently in use by some other I/O port.

<a id="rst-pinmux-conventions"></a>

## Pinmux conventions

The purpose of the pinmux functionality in the pin controller subsystem is to abstract and provide pinmux settings to the devices you choose to instantiate in your machine configuration. It is inspired by the clk, GPIO and regulator subsystems, so devices will request their mux setting, but it's also possible to request a single pin for e.g. GPIO.

The conventions are:

- FUNCTIONS can be switched in and out by a driver residing with the pin control subsystem in the `drivers/pinctrl` directory of the kernel. The pin control driver knows the possible functions. In the example above you can identify three pinmux functions, one for spi, one for i2c and one for mmc.

- FUNCTIONS are assumed to be enumerable from zero in a one-dimensional array. In this case the array could be something like: \{ spi0, i2c0, mmc0 \} for the three available functions.

- FUNCTIONS have PIN GROUPS as defined on the generic level - so a certain function is *always* associated with a certain set of pin groups, could be just a single one, but could also be many. In the example above the function i2c is associated with the pins \{ A5, B5 \}, enumerated as \{ 24, 25 \} in the controller pin space.

  The Function spi is associated with pin groups \{ A8, A7, A6, A5 \} and \{ G4, G3, G2, G1 \}, which are enumerated as \{ 0, 8, 16, 24 \} and \{ 38, 46, 54, 62 \} respectively.

  Group names must be unique per pin controller, no two groups on the same controller may have the same name.

- The combination of a FUNCTION and a PIN GROUP determine a certain function for a certain set of pins. The knowledge of the functions and pin groups and their machine-specific particulars are kept inside the pinmux driver, from the outside only the enumerators are known, and the driver core can request:

  - The name of a function with a certain selector (&gt;= 0)

  - A list of groups associated with a certain function

  - That a certain group in that list to be activated for a certain function

  As already described above, pin groups are in turn self-descriptive, so the core will retrieve the actual pin range in a certain group from the driver.

- FUNCTIONS and GROUPS on a certain PIN CONTROLLER are MAPPED to a certain device by the board file, device tree or similar machine setup configuration mechanism, similar to how regulators are connected to devices, usually by name. Defining a pin controller, function and group thus uniquely identify the set of pins to be used by a certain device. (If only one possible group of pins is available for the function, no group name need to be supplied - the core will simply select the first and only group available.)

  In the example case we can define that this particular machine shall use device spi0 with pinmux function fspi0 group gspi0 and i2c0 on function fi2c0 group gi2c0, on the primary pin controller, we get mappings like these:



  ```c
  {
          {"map-spi0", spi0, pinctrl0, fspi0, gspi0},
          {"map-i2c0", i2c0, pinctrl0, fi2c0, gi2c0},
  }
  ```

  Every map must be assigned a state name, pin controller, device and function. The group is not compulsory - if it is omitted the first group presented by the driver as applicable for the function will be selected, which is useful for simple cases.

  It is possible to map several groups to the same combination of device, pin controller and function. This is for cases where a certain function on a certain pin controller may use different sets of pins in different configurations.

- PINS for a certain FUNCTION using a certain PIN GROUP on a certain PIN CONTROLLER are provided on a first-come first-serve basis, so if some other device mux setting or GPIO pin request has already taken your physical pin, you will be denied the use of it. To get (activate) a new setting, the old one has to be put (deactivated) first.

Sometimes the documentation and hardware registers will be oriented around pads (or "fingers") rather than pins - these are the soldering surfaces on the silicon inside the package, and may or may not match the actual number of pins/balls underneath the capsule. Pick some enumeration that makes sense to you. Define enumerators only for the pins you can control if that makes sense.

Assumptions:

We assume that the number of possible function maps to pin groups is limited by the hardware. I.e. we assume that there is no system where any function can be mapped to any pin, like in a phone exchange. So the available pin groups for a certain function will be limited to a few choices (say up to eight or so), not hundreds or any amount of choices. This is the characteristic we have found by inspecting available pinmux hardware, and a necessary assumption since we expect pinmux drivers to present *all* possible function vs pin group mappings to the subsystem.

<a id="rst-pinmux-drivers"></a>

## Pinmux drivers

The pinmux core takes care of preventing conflicts on pins and calling the pin controller driver to execute different settings.

It is the responsibility of the pinmux driver to impose further restrictions (say for example infer electronic limitations due to load, etc.) to determine whether or not the requested function can actually be allowed, and in case it is possible to perform the requested mux setting, poke the hardware so that this happens.

Pinmux drivers are required to supply a few callback functions, some are optional. Usually the `.set_mux()` function is implemented, writing values into some certain registers to activate a certain mux setting for a certain pin.

A simple driver for the above example will work by setting bits 0, 1, 2, 3, 4, or 5 into some register named MUX to select a certain function with a certain group of pins would work something like this:



```c
#include <linux/pinctrl/pinctrl.h>
#include <linux/pinctrl/pinmux.h>

static const unsigned int spi0_0_pins[] = { 0, 8, 16, 24 };
static const unsigned int spi0_1_pins[] = { 38, 46, 54, 62 };
static const unsigned int i2c0_pins[] = { 24, 25 };
static const unsigned int mmc0_1_pins[] = { 56, 57 };
static const unsigned int mmc0_2_pins[] = { 58, 59 };
static const unsigned int mmc0_3_pins[] = { 60, 61, 62, 63 };

static const struct pingroup foo_groups[] = {
        PINCTRL_PINGROUP("spi0_0_grp", spi0_0_pins, ARRAY_SIZE(spi0_0_pins)),
        PINCTRL_PINGROUP("spi0_1_grp", spi0_1_pins, ARRAY_SIZE(spi0_1_pins)),
        PINCTRL_PINGROUP("i2c0_grp", i2c0_pins, ARRAY_SIZE(i2c0_pins)),
        PINCTRL_PINGROUP("mmc0_1_grp", mmc0_1_pins, ARRAY_SIZE(mmc0_1_pins)),
        PINCTRL_PINGROUP("mmc0_2_grp", mmc0_2_pins, ARRAY_SIZE(mmc0_2_pins)),
        PINCTRL_PINGROUP("mmc0_3_grp", mmc0_3_pins, ARRAY_SIZE(mmc0_3_pins)),
};

static int foo_get_groups_count(struct pinctrl_dev *pctldev)
{
        return ARRAY_SIZE(foo_groups);
}

static const char *foo_get_group_name(struct pinctrl_dev *pctldev,
                                      unsigned int selector)
{
        return foo_groups[selector].name;
}

static int foo_get_group_pins(struct pinctrl_dev *pctldev, unsigned int selector,
                              const unsigned int **pins,
                              unsigned int *npins)
{
        *pins = foo_groups[selector].pins;
        *npins = foo_groups[selector].npins;
        return 0;
}

static struct pinctrl_ops foo_pctrl_ops = {
        .get_groups_count = foo_get_groups_count,
        .get_group_name = foo_get_group_name,
        .get_group_pins = foo_get_group_pins,
};

static const char * const spi0_groups[] = { "spi0_0_grp", "spi0_1_grp" };
static const char * const i2c0_groups[] = { "i2c0_grp" };
static const char * const mmc0_groups[] = { "mmc0_1_grp", "mmc0_2_grp", "mmc0_3_grp" };

static const struct pinfunction foo_functions[] = {
        PINCTRL_PINFUNCTION("spi0", spi0_groups, ARRAY_SIZE(spi0_groups)),
        PINCTRL_PINFUNCTION("i2c0", i2c0_groups, ARRAY_SIZE(i2c0_groups)),
        PINCTRL_PINFUNCTION("mmc0", mmc0_groups, ARRAY_SIZE(mmc0_groups)),
};

static int foo_get_functions_count(struct pinctrl_dev *pctldev)
{
        return ARRAY_SIZE(foo_functions);
}

static const char *foo_get_fname(struct pinctrl_dev *pctldev, unsigned int selector)
{
        return foo_functions[selector].name;
}

static int foo_get_groups(struct pinctrl_dev *pctldev, unsigned int selector,
                          const char * const **groups,
                          unsigned int * const ngroups)
{
        *groups = foo_functions[selector].groups;
        *ngroups = foo_functions[selector].ngroups;
        return 0;
}

static int foo_set_mux(struct pinctrl_dev *pctldev, unsigned int selector,
                       unsigned int group)
{
        u8 regbit = BIT(group);

        writeb((readb(MUX) | regbit), MUX);
        return 0;
}

static struct pinmux_ops foo_pmxops = {
        .get_functions_count = foo_get_functions_count,
        .get_function_name = foo_get_fname,
        .get_function_groups = foo_get_groups,
        .set_mux = foo_set_mux,
        .strict = true,
};

/* Pinmux operations are handled by some pin controller */
static struct pinctrl_desc foo_desc = {
        ...
        .pctlops = &foo_pctrl_ops,
        .pmxops = &foo_pmxops,
};
```

In the example activating muxing 0 and 2 at the same time setting bits 0 and 2, uses pin 24 in common so they would collide. All the same for the muxes 1 and 5, which have pin 62 in common.

The beauty of the pinmux subsystem is that since it keeps track of all pins and who is using them, it will already have denied an impossible request like that, so the driver does not need to worry about such things - when it gets a selector passed in, the pinmux subsystem makes sure no other device or GPIO assignment is already using the selected pins. Thus bits 0 and 2, or 1 and 5 in the control register will never be set at the same time.

All the above functions are mandatory to implement for a pinmux driver.

<a id="rst-pin-control-interaction-with-the-gpio-subsystem"></a>

## Pin control interaction with the GPIO subsystem

Note that the following implies that the use case is to use a certain pin from the Linux kernel using the API in `<linux/gpio/consumer.h>` with gpiod_get() and similar functions. There are cases where you may be using something that your datasheet calls "GPIO mode", but actually is just an electrical configuration for a certain device. See the section below named [GPIO mode pitfalls](<#rst-gpio-mode-pitfalls>) for more details on this scenario.

The public pinmux API contains two functions named `pinctrl_gpio_request()` and `pinctrl_gpio_free()`. These two functions shall *ONLY* be called from gpiolib-based drivers as part of their `.request()` and `.free()` semantics. Likewise the `pinctrl_gpio_direction_input()` / `pinctrl_gpio_direction_output()` shall only be called from within respective `.direction_input()` / `.direction_output()` gpiolib implementation.

NOTE that platforms and individual drivers shall *NOT* request GPIO pins to be controlled e.g. muxed in. Instead, implement a proper gpiolib driver and have that driver request proper muxing and other control for its pins.

The function list could become long, especially if you can convert every individual pin into a GPIO pin independent of any other pins, and then try the approach to define every pin as a function.

In this case, the function array would become 64 entries for each GPIO setting and then the device functions.

For this reason there are two functions a pin control driver can implement to enable only GPIO on an individual pin: `.gpio_request_enable()` and `.gpio_disable_free()`.

This function will pass in the affected GPIO range identified by the pin controller core, so you know which GPIO pins are being affected by the request operation.

If your driver needs to have an indication from the framework of whether the GPIO pin shall be used for input or output you can implement the `.gpio_set_direction()` function. As described this shall be called from the gpiolib driver and the affected GPIO range, pin offset and desired direction will be passed along to this function.

Alternatively to using these special functions, it is fully allowed to use named functions for each GPIO pin, the `pinctrl_gpio_request()` will attempt to obtain the function "gpioN" where "N" is the global GPIO pin number if no special GPIO-handler is registered.

<a id="rst-gpio-mode-pitfalls"></a>

## GPIO mode pitfalls

Due to the naming conventions used by hardware engineers, where "GPIO" is taken to mean different things than what the kernel does, the developer may be confused by a datasheet talking about a pin being possible to set into "GPIO mode". It appears that what hardware engineers mean with "GPIO mode" is not necessarily the use case that is implied in the kernel interface `<linux/gpio/consumer.h>`: a pin that you grab from kernel code and then either listen for input or drive high/low to assert/deassert some external line.

Rather hardware engineers think that "GPIO mode" means that you can software-control a few electrical properties of the pin that you would not be able to control if the pin was in some other mode, such as muxed in for a device.

The GPIO portions of a pin and its relation to a certain pin controller configuration and muxing logic can be constructed in several ways. Here are two examples.

Example **(A)**:



```text
                  pin config
                  logic regs
                  |               +- SPI
Physical pins --- pad --- pinmux -+- I2C
                          |       +- mmc
                          |       +- GPIO
                          pin
                          multiplex
                          logic regs
```

Here some electrical properties of the pin can be configured no matter whether the pin is used for GPIO or not. If you multiplex a GPIO onto a pin, you can also drive it high/low from "GPIO" registers. Alternatively, the pin can be controlled by a certain peripheral, while still applying desired pin config properties. GPIO functionality is thus orthogonal to any other device using the pin.

In this arrangement the registers for the GPIO portions of the pin controller, or the registers for the GPIO hardware module are likely to reside in a separate memory range only intended for GPIO driving, and the register range dealing with pin config and pin multiplexing get placed into a different memory range and a separate section of the data sheet.

A flag "strict" in struct pinmux_ops is available to check and deny simultaneous access to the same pin from GPIO and pin multiplexing consumers on hardware of this type. The pinctrl driver should set this flag accordingly.

Example **(B)**:



```text
                  pin config
                  logic regs
                  |               +- SPI
Physical pins --- pad --- pinmux -+- I2C
                  |       |       +- mmc
                  |       |
                  GPIO    pin
                          multiplex
                          logic regs
```

In this arrangement, the GPIO functionality can always be enabled, such that e.g. a GPIO input can be used to "spy" on the SPI/I2C/MMC signal while it is pulsed out. It is likely possible to disrupt the traffic on the pin by doing wrong things on the GPIO block, as it is never really disconnected. It is possible that the GPIO, pin config and pin multiplex registers are placed into the same memory range and the same section of the data sheet, although that need not be the case.

In some pin controllers, although the physical pins are designed in the same way as (B), the GPIO function still can't be enabled at the same time as the peripheral functions. So again the "strict" flag should be set, denying simultaneous activation by GPIO and other muxed in devices.

From a kernel point of view, however, these are different aspects of the hardware and shall be put into different subsystems:

- Registers (or fields within registers) that control electrical properties of the pin such as biasing and drive strength should be exposed through the pinctrl subsystem, as "pin configuration" settings.

- Registers (or fields within registers) that control muxing of signals from various other HW blocks (e.g. I2C, MMC, or GPIO) onto pins should be exposed through the pinctrl subsystem, as mux functions.

- Registers (or fields within registers) that control GPIO functionality such as setting a GPIO's output value, reading a GPIO's input value, or setting GPIO pin direction should be exposed through the GPIO subsystem, and if they also support interrupt capabilities, through the irqchip abstraction.

Depending on the exact HW register design, some functions exposed by the GPIO subsystem may call into the pinctrl subsystem in order to coordinate register settings across HW modules. In particular, this may be needed for HW with separate GPIO and pin controller HW modules, where e.g. GPIO direction is determined by a register in the pin controller HW module rather than the GPIO HW module.

Electrical properties of the pin such as biasing and drive strength may be placed at some pin-specific register in all cases or as part of the GPIO register in case (B) especially. This doesn't mean that such properties necessarily pertain to what the Linux kernel calls "GPIO".

Example: a pin is usually muxed in to be used as a UART TX line. But during system sleep, we need to put this pin into "GPIO mode" and ground it.

If you make a 1-to-1 map to the GPIO subsystem for this pin, you may start to think that you need to come up with something really complex, that the pin shall be used for UART TX and GPIO at the same time, that you will grab a pin control handle and set it to a certain state to enable UART TX to be muxed in, then twist it over to GPIO mode and use gpiod_direction_output() to drive it low during sleep, then mux it over to UART TX again when you wake up and maybe even gpiod_get() / gpiod_put() as part of this cycle. This all gets very complicated.

The solution is to not think that what the datasheet calls "GPIO mode" has to be handled by the `<linux/gpio/consumer.h>` interface. Instead view this as a certain pin config setting. Look in e.g. `<linux/pinctrl/pinconf-generic.h>` and you find this in the documentation:

> - **PIN_CONFIG_LEVEL:**
>
>   this will configure the pin in output, use argument 1 to indicate high level, argument 0 to indicate low level.

So it is perfectly possible to push a pin into "GPIO mode" and drive the line low as part of the usual pin control map. So for example your UART driver may look like this:



```c
#include <linux/pinctrl/consumer.h>

struct pinctrl          *pinctrl;
struct pinctrl_state    *pins_default;
struct pinctrl_state    *pins_sleep;

pins_default = pinctrl_lookup_state(uap->pinctrl, PINCTRL_STATE_DEFAULT);
pins_sleep = pinctrl_lookup_state(uap->pinctrl, PINCTRL_STATE_SLEEP);

/* Normal mode */
retval = pinctrl_select_state(pinctrl, pins_default);

/* Sleep mode */
retval = pinctrl_select_state(pinctrl, pins_sleep);
```

And your machine configuration may look like this:



```c
static unsigned long uart_default_mode[] = {
        PIN_CONF_PACKED(PIN_CONFIG_DRIVE_PUSH_PULL, 0),
};

static unsigned long uart_sleep_mode[] = {
        PIN_CONF_PACKED(PIN_CONFIG_LEVEL, 0),
};

static struct pinctrl_map pinmap[] __initdata = {
        PIN_MAP_MUX_GROUP("uart", PINCTRL_STATE_DEFAULT, "pinctrl-foo",
                          "u0_group", "u0"),
        PIN_MAP_CONFIGS_PIN("uart", PINCTRL_STATE_DEFAULT, "pinctrl-foo",
                            "UART_TX_PIN", uart_default_mode),
        PIN_MAP_MUX_GROUP("uart", PINCTRL_STATE_SLEEP, "pinctrl-foo",
                          "u0_group", "gpio-mode"),
        PIN_MAP_CONFIGS_PIN("uart", PINCTRL_STATE_SLEEP, "pinctrl-foo",
                            "UART_TX_PIN", uart_sleep_mode),
};

foo_init(void)
{
        pinctrl_register_mappings(pinmap, ARRAY_SIZE(pinmap));
}
```

Here the pins we want to control are in the "u0_group" and there is some function called "u0" that can be enabled on this group of pins, and then everything is UART business as usual. But there is also some function named "gpio-mode" that can be mapped onto the same pins to move them into GPIO mode.

This will give the desired effect without any bogus interaction with the GPIO subsystem. It is just an electrical configuration used by that device when going to sleep, it might imply that the pin is set into something the datasheet calls "GPIO mode", but that is not the point: it is still used by that UART device to control the pins that pertain to that very UART driver, putting them into modes needed by the UART. GPIO in the Linux kernel sense are just some 1-bit line, and is a different use case.

How the registers are poked to attain the push or pull, and output low configuration and the muxing of the "u0" or "gpio-mode" group onto these pins is a question for the driver.

Some datasheets will be more helpful and refer to the "GPIO mode" as "low power mode" rather than anything to do with GPIO. This often means the same thing electrically speaking, but in this latter case the software engineers will usually quickly identify that this is some specific muxing or configuration rather than anything related to the GPIO API.

<a id="rst-board-machine-configuration"></a>

## Board/machine configuration

Boards and machines define how a certain complete running system is put together, including how GPIOs and devices are muxed, how regulators are constrained and how the clock tree looks. Of course pinmux settings are also part of this.

A pin controller configuration for a machine looks pretty much like a simple regulator configuration, so for the example array above we want to enable i2c and spi on the second function mapping:



```c
#include <linux/pinctrl/machine.h>

static const struct pinctrl_map mapping[] __initconst = {
        {
                .dev_name = "foo-spi.0",
                .name = PINCTRL_STATE_DEFAULT,
                .type = PIN_MAP_TYPE_MUX_GROUP,
                .ctrl_dev_name = "pinctrl-foo",
                .data.mux.function = "spi0",
        },
        {
                .dev_name = "foo-i2c.0",
                .name = PINCTRL_STATE_DEFAULT,
                .type = PIN_MAP_TYPE_MUX_GROUP,
                .ctrl_dev_name = "pinctrl-foo",
                .data.mux.function = "i2c0",
        },
        {
                .dev_name = "foo-mmc.0",
                .name = PINCTRL_STATE_DEFAULT,
                .type = PIN_MAP_TYPE_MUX_GROUP,
                .ctrl_dev_name = "pinctrl-foo",
                .data.mux.function = "mmc0",
        },
};
```

The dev_name here matches to the unique device name that can be used to look up the device struct (just like with clockdev or regulators). The function name must match a function provided by the pinmux driver handling this pin range.

As you can see we may have several pin controllers on the system and thus we need to specify which one of them contains the functions we wish to map.

You register this pinmux mapping to the pinmux subsystem by simply:



```c
ret = pinctrl_register_mappings(mapping, ARRAY_SIZE(mapping));
```

Since the above construct is pretty common there is a helper macro to make it even more compact which assumes you want to use pinctrl-foo and position 0 for mapping, for example:



```c
static struct pinctrl_map mapping[] __initdata = {
        PIN_MAP_MUX_GROUP("foo-i2c.0", PINCTRL_STATE_DEFAULT,
                          "pinctrl-foo", NULL, "i2c0"),
};
```

The mapping table may also contain pin configuration entries. It's common for each pin/group to have a number of configuration entries that affect it, so the table entries for configuration reference an array of config parameters and values. An example using the convenience macros is shown below:



```c
static unsigned long i2c_grp_configs[] = {
        FOO_PIN_DRIVEN,
        FOO_PIN_PULLUP,
};

static unsigned long i2c_pin_configs[] = {
        FOO_OPEN_COLLECTOR,
        FOO_SLEW_RATE_SLOW,
};

static struct pinctrl_map mapping[] __initdata = {
        PIN_MAP_MUX_GROUP("foo-i2c.0", PINCTRL_STATE_DEFAULT,
                          "pinctrl-foo", "i2c0", "i2c0"),
        PIN_MAP_CONFIGS_GROUP("foo-i2c.0", PINCTRL_STATE_DEFAULT,
                              "pinctrl-foo", "i2c0", i2c_grp_configs),
        PIN_MAP_CONFIGS_PIN("foo-i2c.0", PINCTRL_STATE_DEFAULT,
                            "pinctrl-foo", "i2c0scl", i2c_pin_configs),
        PIN_MAP_CONFIGS_PIN("foo-i2c.0", PINCTRL_STATE_DEFAULT,
                            "pinctrl-foo", "i2c0sda", i2c_pin_configs),
};
```

Finally, some devices expect the mapping table to contain certain specific named states. When running on hardware that doesn't need any pin controller configuration, the mapping table must still contain those named states, in order to explicitly indicate that the states were provided and intended to be empty. Table entry macro `PIN_MAP_DUMMY_STATE()` serves the purpose of defining a named state without causing any pin controller to be programmed:



```c
static struct pinctrl_map mapping[] __initdata = {
        PIN_MAP_DUMMY_STATE("foo-i2c.0", PINCTRL_STATE_DEFAULT),
};
```

<a id="rst-complex-mappings"></a>

## Complex mappings

As it is possible to map a function to different groups of pins an optional .group can be specified like this:



```c
...
{
        .dev_name = "foo-spi.0",
        .name = "spi0-pos-A",
        .type = PIN_MAP_TYPE_MUX_GROUP,
        .ctrl_dev_name = "pinctrl-foo",
        .function = "spi0",
        .group = "spi0_0_grp",
},
{
        .dev_name = "foo-spi.0",
        .name = "spi0-pos-B",
        .type = PIN_MAP_TYPE_MUX_GROUP,
        .ctrl_dev_name = "pinctrl-foo",
        .function = "spi0",
        .group = "spi0_1_grp",
},
...
```

This example mapping is used to switch between two positions for spi0 at runtime, as described further below under the heading [Runtime pinmuxing](<#rst-runtime-pinmuxing>).

Further it is possible for one named state to affect the muxing of several groups of pins, say for example in the mmc0 example above, where you can additively expand the mmc0 bus from 2 to 4 to 8 pins. If we want to use all three groups for a total of 2 + 2 + 4 = 8 pins (for an 8-bit MMC bus as is the case), we define a mapping like this:



```c
...
{
        .dev_name = "foo-mmc.0",
        .name = "2bit"
        .type = PIN_MAP_TYPE_MUX_GROUP,
        .ctrl_dev_name = "pinctrl-foo",
        .function = "mmc0",
        .group = "mmc0_1_grp",
},
{
        .dev_name = "foo-mmc.0",
        .name = "4bit"
        .type = PIN_MAP_TYPE_MUX_GROUP,
        .ctrl_dev_name = "pinctrl-foo",
        .function = "mmc0",
        .group = "mmc0_1_grp",
},
{
        .dev_name = "foo-mmc.0",
        .name = "4bit"
        .type = PIN_MAP_TYPE_MUX_GROUP,
        .ctrl_dev_name = "pinctrl-foo",
        .function = "mmc0",
        .group = "mmc0_2_grp",
},
{
        .dev_name = "foo-mmc.0",
        .name = "8bit"
        .type = PIN_MAP_TYPE_MUX_GROUP,
        .ctrl_dev_name = "pinctrl-foo",
        .function = "mmc0",
        .group = "mmc0_1_grp",
},
{
        .dev_name = "foo-mmc.0",
        .name = "8bit"
        .type = PIN_MAP_TYPE_MUX_GROUP,
        .ctrl_dev_name = "pinctrl-foo",
        .function = "mmc0",
        .group = "mmc0_2_grp",
},
{
        .dev_name = "foo-mmc.0",
        .name = "8bit"
        .type = PIN_MAP_TYPE_MUX_GROUP,
        .ctrl_dev_name = "pinctrl-foo",
        .function = "mmc0",
        .group = "mmc0_3_grp",
},
...
```

The result of grabbing this mapping from the device with something like this (see next paragraph):



```c
p = devm_pinctrl_get(dev);
s = pinctrl_lookup_state(p, "8bit");
ret = pinctrl_select_state(p, s);
```

or more simply:



```c
p = devm_pinctrl_get_select(dev, "8bit");
```

Will be that you activate all the three bottom records in the mapping at once. Since they share the same name, pin controller device, function and device, and since we allow multiple groups to match to a single device, they all get selected, and they all get enabled and disable simultaneously by the pinmux core.

<a id="rst-pin-control-requests-from-drivers"></a>

## Pin control requests from drivers

When a device driver is about to probe, the device core attaches the standard states if they are defined in the device tree by calling `pinctrl_bind_pins()` on these devices. Possible standard state names are: "default", "init", "sleep" and "idle".

- if `default` is defined in the device tree, it is selected before device probe.

- if `init` and `default` are defined in the device tree, the "init" state is selected before the driver probe and the "default" state is selected after the driver probe.

- the `sleep` and `idle` states are for power management and can only be selected with the PM API bellow.

<a id="rst-pm-interfaces"></a>

## PM interfaces

PM runtime suspend/resume might need to execute the same init sequence as during probe. Since the predefined states are already attached to the device, the driver can activate these states explicitly with the following helper functions:

- `pinctrl_pm_select_default_state()`

- `pinctrl_pm_select_init_state()`

- `pinctrl_pm_select_sleep_state()`

- `pinctrl_pm_select_idle_state()`

For example, if resuming the device depend on certain pinmux states



```c
foo_suspend()
{
        /* suspend device */
        ...

        pinctrl_pm_select_sleep_state(dev);
}

foo_resume()
{
        pinctrl_pm_select_init_state(dev);

        /* resuming device */
        ...

        pinctrl_pm_select_default_state(dev);
}
```

This way driver writers do not need to add any of the boilerplate code of the type found below. However when doing fine-grained state selection and not using the "default" state, you may have to do some device driver handling of the pinctrl handles and states.

So if you just want to put the pins for a certain device into the default state and be done with it, there is nothing you need to do besides providing the proper mapping table. The device core will take care of the rest.

Generally it is discouraged to let individual drivers get and enable pin control. So if possible, handle the pin control in platform code or some other place where you have access to all the affected struct device \* pointers. In some cases where a driver needs to e.g. switch between different mux mappings at runtime this is not possible.

A typical case is if a driver needs to switch bias of pins from normal operation and going to sleep, moving from the `PINCTRL_STATE_DEFAULT` to `PINCTRL_STATE_SLEEP` at runtime, re-biasing or even re-muxing pins to save current in sleep mode.

Another case is when the pinctrl needs to switch to a certain mode during probe and then revert to the default state at the end of probe. For example a PINMUX may need to be configured as a GPIO during probe. In this case, use `PINCTRL_STATE_INIT` to switch state before probe, then move to `PINCTRL_STATE_DEFAULT` at the end of probe for normal operation.

A driver may request a certain control state to be activated, usually just the default state like this:



```c
#include <linux/pinctrl/consumer.h>

struct foo_state {
struct pinctrl *p;
struct pinctrl_state *s;
...
};

foo_probe()
{
        /* Allocate a state holder named "foo" etc */
        struct foo_state *foo = ...;
        int ret;

        foo->p = devm_pinctrl_get(&device);
        if (IS_ERR(foo->p)) {
                ret = PTR_ERR(foo->p);
                foo->p = NULL;
                return ret;
        }

        foo->s = pinctrl_lookup_state(foo->p, PINCTRL_STATE_DEFAULT);
        if (IS_ERR(foo->s)) {
                devm_pinctrl_put(foo->p);
                return PTR_ERR(foo->s);
        }

        ret = pinctrl_select_state(foo->p, foo->s);
        if (ret < 0) {
                devm_pinctrl_put(foo->p);
                return ret;
        }
}
```

This get/lookup/select/put sequence can just as well be handled by bus drivers if you don't want each and every driver to handle it and you know the arrangement on your bus.

The semantics of the pinctrl APIs are:

- `pinctrl_get()` is called in process context to obtain a handle to all pinctrl information for a given client device. It will allocate a struct from the kernel memory to hold the pinmux state. All mapping table parsing or similar slow operations take place within this API.

- `devm_pinctrl_get()` is a variant of pinctrl_get() that causes `pinctrl_put()` to be called automatically on the retrieved pointer when the associated device is removed. It is recommended to use this function over plain `pinctrl_get()`.

- `pinctrl_lookup_state()` is called in process context to obtain a handle to a specific state for a client device. This operation may be slow, too.

- `pinctrl_select_state()` programs pin controller hardware according to the definition of the state as given by the mapping table. In theory, this is a fast-path operation, since it only involved blasting some register settings into hardware. However, note that some pin controllers may have their registers on a slow/IRQ-based bus, so client devices should not assume they can call `pinctrl_select_state()` from non-blocking contexts.

- `pinctrl_put()` frees all information associated with a pinctrl handle.

- `devm_pinctrl_put()` is a variant of `pinctrl_put()` that may be used to explicitly destroy a pinctrl object returned by `devm_pinctrl_get()`. However, use of this function will be rare, due to the automatic cleanup that will occur even without calling it.

  `pinctrl_get()` must be paired with a plain `pinctrl_put()`. `pinctrl_get()` may not be paired with `devm_pinctrl_put()`. `devm_pinctrl_get()` can optionally be paired with `devm_pinctrl_put()`. `devm_pinctrl_get()` may not be paired with plain `pinctrl_put()`.

Usually the pin control core handled the get/put pair and call out to the device drivers bookkeeping operations, like checking available functions and the associated pins, whereas `pinctrl_select_state()` pass on to the pin controller driver which takes care of activating and/or deactivating the mux setting by quickly poking some registers.

The pins are allocated for your device when you issue the `devm_pinctrl_get()` call, after this you should be able to see this in the debugfs listing of all pins.

NOTE: the pinctrl system will return `-EPROBE_DEFER` if it cannot find the requested pinctrl handles, for example if the pinctrl driver has not yet registered. Thus make sure that the error path in your driver gracefully cleans up and is ready to retry the probing later in the startup process.

<a id="rst-drivers-needing-both-pin-control-and-gpios"></a>

## Drivers needing both pin control and GPIOs

Again, it is discouraged to let drivers lookup and select pin control states themselves, but again sometimes this is unavoidable.

So say that your driver is fetching its resources like this:



```c
#include <linux/pinctrl/consumer.h>
#include <linux/gpio/consumer.h>

struct pinctrl *pinctrl;
struct gpio_desc *gpio;

pinctrl = devm_pinctrl_get_select_default(&dev);
gpio = devm_gpiod_get(&dev, "foo");
```

Here we first request a certain pin state and then request GPIO "foo" to be used. If you're using the subsystems orthogonally like this, you should nominally always get your pinctrl handle and select the desired pinctrl state BEFORE requesting the GPIO. This is a semantic convention to avoid situations that can be electrically unpleasant, you will certainly want to mux in and bias pins in a certain way before the GPIO subsystems starts to deal with them.

The above can be hidden: using the device core, the pinctrl core may be setting up the config and muxing for the pins right before the device is probing, nevertheless orthogonal to the GPIO subsystem.

But there are also situations where it makes sense for the GPIO subsystem to communicate directly with the pinctrl subsystem, using the latter as a back-end. This is when the GPIO driver may call out to the functions described in the section [Pin control interaction with the GPIO subsystem](<#rst-pin-control-interaction-with-the-gpio-subsystem>) above. This only involves per-pin multiplexing, and will be completely hidden behind the gpiod\_\*() function namespace. In this case, the driver need not interact with the pin control subsystem at all.

If a pin control driver and a GPIO driver is dealing with the same pins and the use cases involve multiplexing, you MUST implement the pin controller as a back-end for the GPIO driver like this, unless your hardware design is such that the GPIO controller can override the pin controller's multiplexing state through hardware without the need to interact with the pin control system.

<a id="rst-system-pin-control-hogging"></a>

## System pin control hogging

Pin control map entries can be hogged by the core when the pin controller is registered. This means that the core will attempt to call `pinctrl_get()`, `pinctrl_lookup_state()` and `pinctrl_select_state()` on it immediately after the pin control device has been registered.

This occurs for mapping table entries where the client device name is equal to the pin controller device name, and the state name is `PINCTRL_STATE_DEFAULT`:



```c
{
        .dev_name = "pinctrl-foo",
        .name = PINCTRL_STATE_DEFAULT,
        .type = PIN_MAP_TYPE_MUX_GROUP,
        .ctrl_dev_name = "pinctrl-foo",
        .function = "power_func",
},
```

Since it may be common to request the core to hog a few always-applicable mux settings on the primary pin controller, there is a convenience macro for this:



```c
PIN_MAP_MUX_GROUP_HOG_DEFAULT("pinctrl-foo", NULL /* group */,
                              "power_func")
```

This gives the exact same result as the above construction.

<a id="rst-runtime-pinmuxing"></a>

## Runtime pinmuxing

It is possible to mux a certain function in and out at runtime, say to move an SPI port from one set of pins to another set of pins. Say for example for spi0 in the example above, we expose two different groups of pins for the same function, but with different named in the mapping as described under "Advanced mapping" above. So that for an SPI device, we have two states named "pos-A" and "pos-B".

This snippet first initializes a state object for both groups (in foo_probe()), then muxes the function in the pins defined by group A, and finally muxes it in on the pins defined by group B:



```c
#include <linux/pinctrl/consumer.h>

struct pinctrl *p;
struct pinctrl_state *s1, *s2;

foo_probe()
{
        /* Setup */
        p = devm_pinctrl_get(&device);
        if (IS_ERR(p))
                ...

        s1 = pinctrl_lookup_state(p, "pos-A");
        if (IS_ERR(s1))
                ...

        s2 = pinctrl_lookup_state(p, "pos-B");
        if (IS_ERR(s2))
                ...
}

foo_switch()
{
        /* Enable on position A */
        ret = pinctrl_select_state(p, s1);
        if (ret < 0)
                ...

        ...

        /* Enable on position B */
        ret = pinctrl_select_state(p, s2);
        if (ret < 0)
                ...

        ...
}
```

The above has to be done from process context. The reservation of the pins will be done when the state is activated, so in effect one specific pin can be used by different functions at different times on a running system.

<a id="rst-debugfs-files"></a>

## Debugfs files

These files are created in `/sys/kernel/debug/pinctrl`:

- `pinctrl-devices`: prints each pin controller device along with columns to indicate support for pinmux and pinconf

- `pinctrl-handles`: prints each configured pin controller handle and the corresponding pinmux maps

- `pinctrl-maps`: prints all pinctrl maps

A sub-directory is created inside of `/sys/kernel/debug/pinctrl` for each pin controller device containing these files:

- `pins`: prints a line for each pin registered on the pin controller. The pinctrl driver may add additional information such as register contents.

- `gpio-ranges`: prints ranges that map gpio lines to pins on the controller

- `pingroups`: prints all pin groups registered on the pin controller

- `pinconf-pins`: prints pin config settings for each pin

- `pinconf-groups`: prints pin config settings per pin group

- `pinmux-functions`: prints each pin function along with the pin groups that map to the pin function

- `pinmux-pins`: iterates through all pins and prints mux owner, gpio owner and if the pin is a hog

- `pinmux-select`: write to this file to activate a pin function for a group:



  ```sh
  echo "<group-name function-name>" > pinmux-select
  ```

---

# PPS - Pulse Per Second

_Peios Kernel / Hardware and drivers / Driver development / Clocks, signals and platform services_

> Copyright (C) 2007 Rodolfo Giometti <giometti@enneenne.com>

<a id="rst-pps-pulse-per-second"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Copyright (C) 2007 Rodolfo Giometti &lt;[giometti@enneenne.com](<mailto:giometti@enneenne.com>)&gt;

This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more details.

<a id="rst-overview"></a>

## Overview

LinuxPPS provides a programming interface (API) to define in the system several PPS sources.

PPS means "pulse per second" and a PPS source is just a device which provides a high precision signal each second so that an application can use it to adjust system clock time.

A PPS source can be connected to a serial port (usually to the Data Carrier Detect pin) or to a parallel port (ACK-pin) or to a special CPU's GPIOs (this is the common case in embedded systems) but in each case when a new pulse arrives the system must apply to it a timestamp and record it for userland.

Common use is the combination of the NTPD as userland program, with a GPS receiver as PPS source, to obtain a wallclock-time with sub-millisecond synchronisation to UTC.

<a id="rst-rfc-considerations"></a>

## RFC considerations

While implementing a PPS API as RFC 2783 defines and using an embedded CPU GPIO-Pin as physical link to the signal, I encountered a deeper problem:

> At startup it needs a file descriptor as argument for the function time_pps_create().

This implies that the source has a /dev/... entry. This assumption is OK for the serial and parallel port, where you can do something useful besides(\!) the gathering of timestamps as it is the central task for a PPS API. But this assumption does not work for a single purpose GPIO line. In this case even basic file-related functionality (like read() and write()) makes no sense at all and should not be a precondition for the use of a PPS API.

The problem can be simply solved if you consider that a PPS source is not always connected with a GPS data source.

So your programs should check if the GPS data source (the serial port for instance) is a PPS source too, and if not they should provide the possibility to open another device as PPS source.

In LinuxPPS the PPS sources are simply char devices usually mapped into files /dev/pps0, /dev/pps1, etc.

<a id="rst-pps-with-usb-to-serial-devices"></a>

## PPS with USB to serial devices

It is possible to grab the PPS from an USB to serial device. However, you should take into account the latencies and jitter introduced by the USB stack. Users have reported clock instability around +-1ms when synchronized with PPS through USB. With USB 2.0, jitter may decrease down to the order of 125 microseconds.

This may be suitable for time server synchronization with NTP because of its undersampling and algorithms.

If your device doesn't report PPS, you can check that the feature is supported by its driver. Most of the time, you only need to add a call to usb_serial_handle_dcd_change after checking the DCD status (see ch341 and pl2303 examples).

<a id="rst-coding-example"></a>

## Coding example

To register a PPS source into the kernel you should define a struct pps_source_info as follows:



```text
static struct pps_source_info pps_ktimer_info = {
        .name         = "ktimer",
        .path         = "",
        .mode         = PPS_CAPTUREASSERT | PPS_OFFSETASSERT |
                        PPS_ECHOASSERT |
                        PPS_CANWAIT | PPS_TSFMT_TSPEC,
        .echo         = pps_ktimer_echo,
        .owner        = THIS_MODULE,
};
```

and then calling the function pps_register_source() in your initialization routine as follows:



```text
source = pps_register_source(&pps_ktimer_info,
                    PPS_CAPTUREASSERT | PPS_OFFSETASSERT);
```

The pps_register_source() prototype is:



```text
int pps_register_source(struct pps_source_info *info, int default_params)
```

where "info" is a pointer to a structure that describes a particular PPS source, "default_params" tells the system what the initial default parameters for the device should be (it is obvious that these parameters must be a subset of ones defined in the struct pps_source_info which describe the capabilities of the driver).

Once you have registered a new PPS source into the system you can signal an assert event (for example in the interrupt handler routine) just using:



```text
pps_event(source, &ts, PPS_CAPTUREASSERT, ptr)
```

where "ts" is the event's timestamp.

The same function may also run the defined echo function (pps_ktimer_echo(), passing to it the "ptr" pointer) if the user asked for that... etc..

Please see the file drivers/pps/clients/pps-ktimer.c for example code.

<a id="rst-sysfs-support"></a>

## SYSFS support

If the SYSFS filesystem is enabled in the kernel it provides a new class:



```text
$ ls /sys/class/pps/
pps0/  pps1/  pps2/
```

Every directory is the ID of a PPS sources defined in the system and inside you find several files:



```text
$ ls -F /sys/class/pps/pps0/
assert     dev        mode       path       subsystem@
clear      echo       name       power/     uevent
```

Inside each "assert" and "clear" file you can find the timestamp and a sequence number:



```text
$ cat /sys/class/pps/pps0/assert
1170026870.983207967#8
```

Where before the "\#" is the timestamp in seconds; after it is the sequence number. Other files are:

> - echo: reports if the PPS source has an echo function or not;
>
> - mode: reports available PPS functioning modes;
>
> - name: reports the PPS source's name;
>
> - path: reports the PPS source's device path, that is the device the PPS source is connected to (if it exists).

<a id="rst-testing-the-pps-support"></a>

## Testing the PPS support

In order to test the PPS support even without specific hardware you can use the pps-ktimer driver (see the client subsection in the PPS configuration menu) and the userland tools available in your distribution's pps-tools package, [http://linuxpps.org](<http://linuxpps.org>) , or [https://github.com/redlab-i/pps-tools](<https://github.com/redlab-i/pps-tools>).

Once you have enabled the compilation of pps-ktimer just modprobe it (if not statically compiled):



```text
# modprobe pps-ktimer
```

and the run ppstest as follow:



```text
$ ./ppstest /dev/pps1
trying PPS source "/dev/pps1"
found PPS source "/dev/pps1"
ok, found 1 source(s), now start fetching data...
source 0 - assert 1186592699.388832443, sequence: 364 - clear  0.000000000, sequence: 0
source 0 - assert 1186592700.388931295, sequence: 365 - clear  0.000000000, sequence: 0
source 0 - assert 1186592701.389032765, sequence: 366 - clear  0.000000000, sequence: 0
```

Please note that to compile userland programs, you need the file timepps.h. This is available in the pps-tools repository mentioned above.

<a id="rst-generators"></a>

## Generators

Sometimes one needs to be able not only to catch PPS signals but to produce them also. For example, running a distributed simulation, which requires computers' clock to be synchronized very tightly.

To do so the class pps-gen has been added. PPS generators can be registered in the kernel by defining a struct pps_gen_source_info as follows:



```text
static const struct pps_gen_source_info pps_gen_dummy_info = {
        .use_system_clock       = true,
        .get_time               = pps_gen_dummy_get_time,
        .enable                 = pps_gen_dummy_enable,
};
```

Where the use_system_clock states if the generator uses the system clock to generate its pulses, or they are from a peripheral device clock. Method get_time() is used to query the time stored into the generator clock, while the method enable() is used to enable or disable the PPS pulse generation.

Then calling the function pps_gen_register_source() in your initialization routine as follows creates a new generator in the system:



```text
pps_gen = pps_gen_register_source(&pps_gen_dummy_info);
```

<a id="rst-generators-sysfs-support"></a>

## Generators SYSFS support

If the SYSFS filesystem is enabled in the kernel it provides a new class:



```text
$ ls /sys/class/pps-gen/
pps-gen0/  pps-gen1/  pps-gen2/
```

Every directory is the ID of a PPS generator defined in the system and inside of it you find several files:



```text
$ ls -F /sys/class/pps-gen/pps-gen0/
dev  enable  name  power/  subsystem@  system  time  uevent
```

To enable the PPS signal generation you can use the command below:



```text
$ echo 1 > /sys/class/pps-gen/pps-gen0/enable
```

<a id="rst-parallel-port-generator"></a>

## Parallel port generator

One way to do this is to invent some complicated hardware solutions but it may be neither necessary nor affordable. The cheap way is to load a PPS generator on one of the computers (master) and PPS clients on others (slaves), and use very simple cables to deliver signals using parallel ports, for example.

Parallel port cable pinout:



```text
pin     name    master      slave
1       STROBE    *------     *
2       D0        *     |     *
3       D1        *     |     *
4       D2        *     |     *
5       D3        *     |     *
6       D4        *     |     *
7       D5        *     |     *
8       D6        *     |     *
9       D7        *     |     *
10      ACK       *     ------*
11      BUSY      *           *
12      PE        *           *
13      SEL       *           *
14      AUTOFD    *           *
15      ERROR     *           *
16      INIT      *           *
17      SELIN     *           *
18-25   GND       *-----------*
```

Please note that parallel port interrupt occurs only on high-&gt;low transition, so it is used for PPS assert edge. PPS clear edge can be determined only using polling in the interrupt handler which actually can be done way more precisely because interrupt handling delays can be quite big and random. So current parport PPS generator implementation (pps_gen_parport module) is geared towards using the clear edge for time synchronization.

Clear edge polling is done with disabled interrupts so it's better to select delay between assert and clear edge as small as possible to reduce system latencies. But if it is too small slave won't be able to capture clear edge transition. The default of 30us should be good enough in most situations. The delay can be selected using 'delay' pps_gen_parport module parameter.

<a id="rst-intel-timed-i-o-pps-signal-generator"></a>

## Intel Timed I/O PPS signal generator

Intel Timed I/O is a high precision device, present on 2019 and newer Intel CPUs, that can generate PPS signals.

Timed I/O and system time are both driven by same hardware clock. The signal is generated with a precision of \~20 nanoseconds. The generated PPS signal is used to synchronize an external device with system clock. For example, it can be used to share your clock with a device that receives PPS signal, generated by Timed I/O device. There are dedicated Timed I/O pins to deliver the PPS signal to an external device.

Usage of Intel Timed I/O as PPS generator:

Start generating PPS signal:



```text
$echo 1 > /sys/class/pps-gen/pps-genx/enable
```

Stop generating PPS signal:



```text
$echo 0 > /sys/class/pps-gen/pps-genx/enable
```

---

# PTP hardware clock infrastructure for Linux

_Peios Kernel / Hardware and drivers / Driver development / Clocks, signals and platform services_

> This patch set introduces support for IEEE 1588 PTP clocks in Linux. Together with the SO_TIMESTAMPING socket options, this presents a standardized method for developing PTP user space programs, synchronizing Linux with external clocks,…

<a id="rst-ptp-hardware-clock-infrastructure-for-linux"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

> This patch set introduces support for IEEE 1588 PTP clocks in Linux. Together with the SO_TIMESTAMPING socket options, this presents a standardized method for developing PTP user space programs, synchronizing Linux with external clocks, and using the ancillary features of PTP hardware clocks.
>
> A new class driver exports a kernel interface for specific clock drivers and a user space interface. The infrastructure supports a complete set of PTP hardware clock functionality.
>
> - Basic clock operations - Set time - Get time - Shift the clock by a given offset atomically - Adjust clock frequency
>
> - Ancillary clock features - Time stamp external events - Period output signals configurable from user space - Low Pass Filter (LPF) access from user space - Synchronization of the Linux system time via the PPS subsystem

<a id="rst-ptp-hardware-clock-kernel-api"></a>

## PTP hardware clock kernel API

> A PTP clock driver registers itself with the class driver. The class driver handles all of the dealings with user space. The author of a clock driver need only implement the details of programming the clock hardware. The clock driver notifies the class driver of asynchronous events (alarms and external time stamps) via a simple message passing interface.
>
> The class driver supports multiple PTP clock drivers. In normal use cases, only one PTP clock is needed. However, for testing and development, it can be useful to have more than one clock in a single system, in order to allow performance comparisons.

<a id="rst-ptp-hardware-clock-user-space-api"></a>

## PTP hardware clock user space API

> The class driver also creates a character device for each registered clock. User space can use an open file descriptor from the character device as a POSIX clock id and may call clock_gettime, clock_settime, and clock_adjtime.  These calls implement the basic clock operations.
>
> User space programs may control the clock using standardized ioctls. A program may query, enable, configure, and disable the ancillary clock features. User space can receive time stamped events via blocking read() and poll().

<a id="rst-writing-clock-drivers"></a>

## Writing clock drivers

> Clock drivers include include/linux/ptp_clock_kernel.h and register themselves by presenting a 'struct ptp_clock_info' to the registration method. Clock drivers must implement all of the functions in the interface. If a clock does not offer a particular ancillary feature, then the driver should just return -EOPNOTSUPP from those functions.
>
> Drivers must ensure that all of the methods in interface are reentrant. Since most hardware implementations treat the time value as a 64 bit integer accessed as two 32 bit registers, drivers should use spin_lock_irqsave/spin_unlock_irqrestore to protect against concurrent access. This locking cannot be accomplished in class driver, since the lock may also be needed by the clock driver's interrupt service routine.

<a id="rst-ptp-hardware-clock-requirements-for-adjphase"></a>

### PTP hardware clock requirements for '.adjphase'

> The 'struct ptp_clock_info' interface has a '.adjphase' function. This function has a set of requirements from the PHC in order to be implemented.
>
> > - The PHC implements a servo algorithm internally that is used to correct the offset passed in the '.adjphase' call.
> >
> > - When other PTP adjustment functions are called, the PHC servo algorithm is disabled.
>
> **NOTE:** '.adjphase' is not a simple time adjustment functionality that 'jumps' the PHC clock time based on the provided offset. It should correct the offset provided using an internal algorithm.

<a id="rst-supported-hardware"></a>

## Supported hardware

> - Freescale eTSEC gianfar
>
>   - 2 Time stamp external triggers, programmable polarity (opt. interrupt)
>
>   - 2 Alarm registers (optional interrupt)
>
>   - 3 Periodic signals (optional interrupt)
>
> - National DP83640
>
>   - 6 GPIOs programmable as inputs or outputs
>
>   - 6 GPIOs with dedicated functions (LED/JTAG/clock) can also be used as general inputs or outputs
>
>   - GPIO inputs can time stamp external triggers
>
>   - GPIO outputs can produce periodic signals
>
>   - 1 interrupt pin
>
> - Intel IXP465
>
>   - Auxiliary Slave/Master Mode Snapshot (optional interrupt)
>
>   - Target Time (optional interrupt)
>
> - Renesas (IDT) ClockMatrix™
>
>   - Up to 4 independent PHC channels
>
>   - Integrated low pass filter (LPF), access via .adjPhase (compliant to ITU-T G.8273.2)
>
>   - Programmable output periodic signals
>
>   - Programmable inputs can time stamp external triggers
>
>   - - **Driver and/or hardware configuration through firmware (idtcm.bin)**
>
>       - LPF settings (bandwidth, phase limiting, automatic holdover, physical layer assist (per ITU-T G.8273.2))
>
>       - Programmable output PTP clocks, any frequency up to 1GHz (to other PHY/MAC time stampers, refclk to ASSPs/SoCs/FPGAs)
>
>       - Lock to GNSS input, automatic switching between GNSS and user-space PHC control (optional)
>
> - NVIDIA Mellanox
>
>   - - **GPIO**
>
>       - Certain variants of ConnectX-6 Dx and later products support one GPIO which can time stamp external triggers and one GPIO to produce periodic signals.
>
>       - Certain variants of ConnectX-5 and older products support one GPIO, configured to either time stamp external triggers or produce periodic signals.
>
>   - - **PHC instances**
>
>       - All ConnectX devices have a free-running counter
>
>       - ConnectX-6 Dx and later devices have a UTC format counter

---

# Pulse Width Modulation (PWM) interface

_Peios Kernel / Hardware and drivers / Driver development / Clocks, signals and platform services_

> This provides an overview about the Linux PWM interface

<a id="rst-pulse-width-modulation-pwm-interface"></a>

This provides an overview about the Linux PWM interface

PWMs are commonly used for controlling LEDs, fans or vibrators in cell phones. PWMs with a fixed purpose have no need implementing the Linux PWM API (although they could). However, PWMs are often found as discrete devices on SoCs which have no fixed purpose. It's up to the board designer to connect them to LEDs or fans. To provide this kind of flexibility the generic PWM API exists.

<a id="rst-identifying-pwms"></a>

## Identifying PWMs

Users of the legacy PWM API use unique IDs to refer to PWM devices.

Instead of referring to a PWM device via its unique ID, board setup code should instead register a static mapping that can be used to match PWM consumers to providers, as given in the following example:



```text
static struct pwm_lookup board_pwm_lookup[] = {
        PWM_LOOKUP("tegra-pwm", 0, "pwm-backlight", NULL,
                   50000, PWM_POLARITY_NORMAL),
};

static void __init board_init(void)
{
        ...
        pwm_add_table(board_pwm_lookup, ARRAY_SIZE(board_pwm_lookup));
        ...
}
```

<a id="rst-using-pwms"></a>

## Using PWMs

Consumers use the pwm_get() function and pass to it the consumer device or a consumer name. pwm_put() is used to free the PWM device. Managed variants of the getter, devm_pwm_get() and devm_fwnode_pwm_get(), also exist.

After being requested, a PWM has to be configured using:



```text
int pwm_apply_might_sleep(struct pwm_device *pwm, struct pwm_state *state);
```

This API controls both the PWM period/duty_cycle config and the enable/disable state.

PWM devices can be used from atomic context, if the PWM does not sleep. You can check if this the case with:



```text
bool pwm_might_sleep(struct pwm_device *pwm);
```

If false, the PWM can also be configured from atomic context with:



```text
int pwm_apply_atomic(struct pwm_device *pwm, struct pwm_state *state);
```

As a consumer, don't rely on the output's state for a disabled PWM. If it's easily possible, drivers are supposed to emit the inactive state, but some drivers cannot. If you rely on getting the inactive state, use .duty_cycle=0, .enabled=true.

There is also a usage_power setting: If set, the PWM driver is only required to maintain the power output but has more freedom regarding signal form. If supported by the driver, the signal can be optimized, for example to improve EMI by phase shifting the individual channels of a chip.

The pwm_config(), pwm_enable() and pwm_disable() functions are just wrappers around pwm_apply_might_sleep() and should not be used if the user wants to change several parameter at once. For example, if you see pwm_config() and pwm\_\{enable,disable\}() calls in the same function, this probably means you should switch to pwm_apply_might_sleep().

The PWM user API also allows one to query the PWM state that was passed to the last invocation of pwm_apply_might_sleep() using pwm_get_state(). Note this is different to what the driver has actually implemented if the request cannot be satisfied exactly with the hardware in use. There is currently no way for consumers to get the actually implemented settings.

In addition to the PWM state, the PWM API also exposes PWM arguments, which are the reference PWM config one should use on this PWM. PWM arguments are usually platform-specific and allows the PWM user to only care about dutycycle relatively to the full period (like, duty = 50% of the period). struct pwm_args contains 2 fields (period and polarity) and should be used to set the initial PWM config (usually done in the probe function of the PWM user). PWM arguments are retrieved with pwm_get_args().

All consumers should really be reconfiguring the PWM upon resume as appropriate. This is the only way to ensure that everything is resumed in the proper order.

<a id="rst-using-pwms-with-the-sysfs-interface"></a>

## Using PWMs with the sysfs interface

If CONFIG_SYSFS is enabled in your kernel configuration a simple sysfs interface is provided to use the PWMs from userspace. It is exposed at /sys/class/pwm/. Each probed PWM controller/chip will be exported as pwmchipN, where N is the base of the PWM chip. Inside the directory you will find:

> - **npwm**
>
>   The number of PWM channels this chip supports (read-only).
>
> - **export**
>
>   Exports a PWM channel for use with sysfs (write-only).
>
> - **unexport**
>
>   Unexports a PWM channel from sysfs (write-only).

The PWM channels are numbered using a per-chip index from 0 to npwm-1.

When a PWM channel is exported a pwmX directory will be created in the pwmchipN directory it is associated with, where X is the number of the channel that was exported. The following properties will then be available:

> - **period**
>
>   The total period of the PWM signal (read/write). Value is in nanoseconds and is the sum of the active and inactive time of the PWM.
>
> - **duty_cycle**
>
>   The active time of the PWM signal (read/write). Value is in nanoseconds and must be less than or equal to the period.
>
> - **polarity**
>
>   Changes the polarity of the PWM signal (read/write). Writes to this property only work if the PWM chip supports changing the polarity. Value is the string "normal" or "inversed".
>
> - **enable**
>
>   Enable/disable the PWM signal (read/write).
>
>   > - 0 - disabled
>   >
>   > - 1 - enabled

<a id="rst-implementing-a-pwm-driver"></a>

## Implementing a PWM driver

Currently there are two ways to implement pwm drivers. Traditionally there only has been the barebone API meaning that each driver has to implement the pwm\_\*() functions itself. This means that it's impossible to have multiple PWM drivers in the system. For this reason it's mandatory for new drivers to use the generic PWM framework.

A new PWM controller/chip can be allocated using pwmchip_alloc(), then registered using pwmchip_add() and removed again with pwmchip_remove(). To undo pwmchip_alloc() use pwmchip_put(). pwmchip_add() takes a filled in struct pwm_chip as argument which provides a description of the PWM chip, the number of PWM devices provided by the chip and the chip-specific implementation of the supported PWM operations to the framework.

When implementing polarity support in a PWM driver, make sure to respect the signal conventions in the PWM framework. By definition, normal polarity characterizes a signal starts high for the duration of the duty cycle and goes low for the remainder of the period. Conversely, a signal with inversed polarity starts low for the duration of the duty cycle and goes high for the remainder of the period.

Drivers are encouraged to implement -&gt;apply() instead of the legacy -&gt;enable(), -&gt;disable() and -&gt;config() methods. Doing that should provide atomicity in the PWM config workflow, which is required when the PWM controls a critical device (like a regulator).

The implementation of -&gt;get_state() (a method used to retrieve initial PWM state) is also encouraged for the same reason: letting the PWM user know about the current PWM state would allow him to avoid glitches.

Drivers should not implement any power management. In other words, consumers should implement it as described in the "Using PWMs" section.

<a id="rst-locking"></a>

## Locking

The PWM core list manipulations are protected by a mutex, so pwm_get() and pwm_put() may not be called from an atomic context. Most functions in the PWM consumer API might sleep and so must not be called from atomic context. The notable exception is pwm_apply_atomic() which has the same semantics as pwm_apply_might_sleep() but can be called from atomic context. (The price for that is that it doesn't work for all PWM devices, use pwm_might_sleep() to check if a given PWM supports atomic operation.

Locking in the PWM core ensures that callbacks related to a single chip are serialized.

<a id="rst-helpers"></a>

## Helpers

Currently a PWM can only be configured with period_ns and duty_ns. For several use cases freq_hz and duty_percent might be better. Instead of calculating this in your driver please consider adding appropriate helpers to the framework.

---

# Power Sequencing API

_Peios Kernel / Hardware and drivers / Driver development / Clocks, signals and platform services_

> This framework is designed to abstract complex power-up sequences that are shared between multiple logical devices in the Linux kernel.

<a id="rst-power-sequencing-api"></a>

<!-- SPDX-License-Identifier: GPL-2.0-only -->

<!-- Copyright 2024 Linaro Ltd. -->

**Author:** Bartosz Golaszewski

<a id="rst-introduction"></a>

## Introduction

This framework is designed to abstract complex power-up sequences that are shared between multiple logical devices in the Linux kernel.

The intention is to allow consumers to obtain a power sequencing handle exposed by the power sequence provider and delegate the actual requesting and control of the underlying resources as well as to allow the provider to mitigate any potential conflicts between multiple users behind the scenes.

<a id="rst-glossary"></a>

### Glossary

The power sequencing API uses a number of terms specific to the subsystem:

Unit

> A unit is a discrete chunk of a power sequence. For instance one unit may enable a set of regulators, another may enable a specific GPIO. Units can define dependencies in the form of other units that must be enabled before it itself can be.

Target

> A target is a set of units (composed of the "final" unit and its dependencies) that a consumer selects by its name when requesting a handle to the power sequencer. Via the dependency system, multiple targets may share the same parts of a power sequence but ignore parts that are irrelevant.

Descriptor

> A handle passed by the pwrseq core to every consumer that serves as the entry point to the provider layer. It ensures coherence between different users and keeps reference counting consistent.

<a id="rst-consumer-interface"></a>

## Consumer interface

The consumer API is aimed to be as simple as possible. The driver interested in getting a descriptor from the power sequencer should call pwrseq_get() and specify the name of the target it wants to reach in the sequence after calling pwrseq_power_up(). The descriptor can be released by calling pwrseq_put() and the consumer can request the powering down of its target with pwrseq_power_off(). Note that there is no guarantee that pwrseq_power_off() will have any effect as there may be multiple users of the underlying resources who may keep them active.

<a id="rst-provider-interface"></a>

## Provider interface

The provider API is admittedly not nearly as straightforward as the one for consumers but it makes up for it in flexibility.

Each provider can logically split the power-up sequence into discrete chunks (units) and define their dependencies. They can then expose named targets that consumers may use as the final point in the sequence that they wish to reach.

To that end the providers fill out a set of configuration structures and register with the pwrseq subsystem by calling pwrseq_device_register().

<a id="rst-dynamic-consumer-matching"></a>

### Dynamic consumer matching

The main difference between pwrseq and other Linux kernel providers is the mechanism for dynamic matching of consumers and providers. Every power sequence provider driver must implement the `match()` callback and pass it to the pwrseq core when registering with the subsystems.

When a client requests a sequencer handle, the core will call this callback for every registered provider and let it flexibly figure out whether the proposed client device is indeed its consumer. For example: if the provider binds to the device-tree node representing a power management unit of a chipset and the consumer driver controls one of its modules, the provider driver may parse the relevant regulator supply properties in device tree and see if they lead from the PMU to the consumer.

<a id="rst-api-reference"></a>

## API reference


#### <a id="c-struct-pwrseq_unit_data"></a>`struct pwrseq_unit_data`

Configuration of a single power sequencing unit.

**Definition**

```c
struct pwrseq_unit_data {
    const char *name;
    const struct pwrseq_unit_data **deps;
    pwrseq_power_state_func enable;
    pwrseq_power_state_func disable;
};
```

**Members**

- `name`: Name of the unit.
- `deps`: Units that must be enabled before this one and disabled after it
  in the order they come in this array. Must be NULL-terminated.
- `enable`: Callback running the part of the power-on sequence provided by
  this unit.
- `disable`: Callback running the part of the power-off sequence provided
  by this unit.

#### <a id="c-struct-pwrseq_target_data"></a>`struct pwrseq_target_data`

Configuration of a power sequencing target.

**Definition**

```c
struct pwrseq_target_data {
    const char *name;
    const struct pwrseq_unit_data *unit;
    pwrseq_power_state_func post_enable;
};
```

**Members**

- `name`: Name of the target.
- `unit`: Final unit that this target must reach in order to be considered
  enabled.
- `post_enable`: Callback run after the target unit has been enabled, *after*
  the state lock has been released. It's useful for implementing
  boot-up delays without blocking other users from powering up
  using the same power sequencer.

#### <a id="c-struct-pwrseq_config"></a>`struct pwrseq_config`

Configuration used for registering a new provider.

**Definition**

```c
struct pwrseq_config {
    struct device *parent;
    struct module *owner;
    void *drvdata;
    pwrseq_match_func match;
    const struct pwrseq_target_data **targets;
};
```

**Members**

- `parent`: Parent device for the sequencer. Must be set.
- `owner`: Module providing this device.
- `drvdata`: Private driver data.
- `match`: Provider callback used to match the consumer device to the sequencer.
- `targets`: Array of targets for this power sequencer. Must be NULL-terminated.



#### <a id="c-pwrseq_device_register"></a>`pwrseq_device_register()`

```c
struct pwrseq_device * pwrseq_device_register(const struct pwrseq_config *config)
```

Register a new power sequencer.

**Parameters**

- `const struct pwrseq_config *config`: Configuration of the new power sequencing device.

**Description**

The config structure is only used during the call and can be freed after
the function returns. The config structure *must* have the parent device
as well as the `match()` callback and at least one target set.

**Return**

Returns the address of the new pwrseq device or [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR) on failure.

#### <a id="c-pwrseq_device_unregister"></a>`pwrseq_device_unregister()`

```c
void pwrseq_device_unregister(struct pwrseq_device *pwrseq)
```

Unregister the power sequencer.

**Parameters**

- `struct pwrseq_device *pwrseq`: Power sequencer to unregister.

#### <a id="c-devm_pwrseq_device_register"></a>`devm_pwrseq_device_register()`

```c
struct pwrseq_device * devm_pwrseq_device_register(struct device *dev, const struct pwrseq_config *config)
```

Managed variant of [`pwrseq_device_register()`](#c-pwrseq_device_register).

**Parameters**

- `struct device *dev`: Managing device.
- `const struct pwrseq_config *config`: Configuration of the new power sequencing device.

**Return**

Returns the address of the new pwrseq device or [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR) on failure.

#### <a id="c-pwrseq_device_get_drvdata"></a>`pwrseq_device_get_drvdata()`

```c
void * pwrseq_device_get_drvdata(struct pwrseq_device *pwrseq)
```

Get the driver private data associated with this sequencer.

**Parameters**

- `struct pwrseq_device *pwrseq`: Power sequencer object.

**Return**

Address of the private driver data.

#### <a id="c-pwrseq_get"></a>`pwrseq_get()`

```c
struct pwrseq_desc * pwrseq_get(struct device *dev, const char *target)
```

Get the power sequencer associated with this device.

**Parameters**

- `struct device *dev`: Device for which to get the sequencer.
- `const char *target`: Name of the target exposed by the sequencer this device wants to
  reach.

**Return**

New power sequencer descriptor for use by the consumer driver or [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR)
on failure.

#### <a id="c-pwrseq_put"></a>`pwrseq_put()`

```c
void pwrseq_put(struct pwrseq_desc *desc)
```

Release the power sequencer descriptor.

**Parameters**

- `struct pwrseq_desc *desc`: Descriptor to release.

#### <a id="c-devm_pwrseq_get"></a>`devm_pwrseq_get()`

```c
struct pwrseq_desc * devm_pwrseq_get(struct device *dev, const char *target)
```

Managed variant of [`pwrseq_get()`](#c-pwrseq_get).

**Parameters**

- `struct device *dev`: Device for which to get the sequencer and which also manages its
  lifetime.
- `const char *target`: Name of the target exposed by the sequencer this device wants to
  reach.

**Return**

New power sequencer descriptor for use by the consumer driver or [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR)
on failure.

#### <a id="c-pwrseq_power_on"></a>`pwrseq_power_on()`

```c
int pwrseq_power_on(struct pwrseq_desc *desc)
```

Issue a power-on request on behalf of the consumer device.

**Parameters**

- `struct pwrseq_desc *desc`: Descriptor referencing the power sequencer.

**Description**

This function tells the power sequencer that the consumer wants to be
powered-up. The sequencer may already have powered-up the device in which
case the function returns 0. If the power-up sequence is already in
progress, the function will block until it's done and return 0. If this is
the first request, the device will be powered up.

**Return**

0 on success, negative error number on failure.

#### <a id="c-pwrseq_power_off"></a>`pwrseq_power_off()`

```c
int pwrseq_power_off(struct pwrseq_desc *desc)
```

Issue a power-off request on behalf of the consumer device.

**Parameters**

- `struct pwrseq_desc *desc`: Descriptor referencing the power sequencer.

**Description**

This undoes the effects of [`pwrseq_power_on()`](#c-pwrseq_power_on). It issues a power-off request
on behalf of the consumer and when the last remaining user does so, the
power-down sequence will be started. If one is in progress, the function
will block until it's complete and then return.

**Return**

0 on success, negative error number on failure.

---

# Voltage and current regulator API

_Peios Kernel / Hardware and drivers / Driver development / Clocks, signals and platform services_

> This framework is designed to provide a standard kernel interface to control voltage and current regulators.

<a id="rst-voltage-and-current-regulator-api"></a>

<!-- Copyright 2007-2008 Wolfson Microelectronics -->

<!-- This documentation is free software; you can redistribute -->

<!-- it and/or modify it under the terms of the GNU General Public -->

<!-- License version 2 as published by the Free Software Foundation. -->

**Author:** Liam Girdwood

**Author:** Mark Brown

<a id="rst-introduction"></a>

## Introduction

This framework is designed to provide a standard kernel interface to control voltage and current regulators.

The intention is to allow systems to dynamically control regulator power output in order to save power and prolong battery life. This applies to both voltage regulators (where voltage output is controllable) and current sinks (where current limit is controllable).

Note that additional (and currently more complete) documentation is available in the Linux kernel source under `Documentation/power/regulator`.

<a id="rst-glossary"></a>

### Glossary

The regulator API uses a number of terms which may not be familiar:

Regulator

> Electronic device that supplies power to other devices. Most regulators can enable and disable their output and some can also control their output voltage or current.

Consumer

> Electronic device which consumes power provided by a regulator. These may either be static, requiring only a fixed supply, or dynamic, requiring active management of the regulator at runtime.

Power Domain

> The electronic circuit supplied by a given regulator, including the regulator and all consumer devices. The configuration of the regulator is shared between all the components in the circuit.

Power Management Integrated Circuit (PMIC)

> An IC which contains numerous regulators and often also other subsystems. In an embedded system the primary PMIC is often equivalent to a combination of the PSU and southbridge in a desktop system.

<a id="rst-consumer-driver-interface"></a>

## Consumer driver interface

This offers a similar API to the kernel clock framework. Consumer drivers use [get](#c-regulator_get) and [put](#c-regulator_put) operations to acquire and release regulators. Functions are provided to [enable](#c-regulator_enable) and [disable](#c-regulator_disable) the regulator and to get and set the runtime parameters of the regulator.

When requesting regulators consumers use symbolic names for their supplies, such as "Vcc", which are mapped into actual regulator devices by the machine interface.

A stub version of this API is provided when the regulator framework is not in use in order to minimise the need to use ifdefs.

<a id="rst-enabling-and-disabling"></a>

### Enabling and disabling

The regulator API provides reference counted enabling and disabling of regulators. Consumer devices use the `regulator_enable()` and `regulator_disable()` functions to enable and disable regulators. Calls to the two functions must be balanced.

Note that since multiple consumers may be using a regulator and machine constraints may not allow the regulator to be disabled there is no guarantee that calling `regulator_disable()` will actually cause the supply provided by the regulator to be disabled. Consumer drivers should assume that the regulator may be enabled at all times.

<a id="rst-configuration"></a>

### Configuration

Some consumer devices may need to be able to dynamically configure their supplies. For example, MMC drivers may need to select the correct operating voltage for their cards. This may be done while the regulator is enabled or disabled.

The `regulator_set_voltage()` and `regulator_set_current_limit()` functions provide the primary interface for this. Both take ranges of voltages and currents, supporting drivers that do not require a specific value (eg, CPU frequency scaling normally permits the CPU to use a wider range of supply voltages at lower frequencies but does not require that the supply voltage be lowered). Where an exact value is required both minimum and maximum values should be identical.

<a id="rst-callbacks"></a>

### Callbacks

Callbacks may also be registered for events such as regulation failures.

<a id="rst-regulator-driver-interface"></a>

## Regulator driver interface

Drivers for regulator chips register the regulators with the regulator core, providing operations structures to the core. A notifier interface allows error conditions to be reported to the core.

Registration should be triggered by explicit setup done by the platform, supplying a struct regulator_init_data for the regulator containing constraint and supply information.

<a id="rst-machine-interface"></a>

## Machine interface

This interface provides a way to define how regulators are connected to consumers on a given system and what the valid operating parameters are for the system.

<a id="rst-supplies"></a>

### Supplies

Regulator supplies are specified using struct `regulator_consumer_supply`. This is done at driver registration time as part of the machine constraints.

<a id="rst-constraints"></a>

### Constraints

As well as defining the connections the machine interface also provides constraints defining the operations that clients are allowed to perform and the parameters that may be set. This is required since generally regulator devices will offer more flexibility than it is safe to use on a given system, for example supporting higher supply voltages than the consumers are rated for.

This is done at driver registration time\` by providing a struct regulation_constraints.

The constraints may also specify an initial configuration for the regulator in the constraints, which is particularly useful for use with static consumers.

<a id="rst-api-reference"></a>

## API reference

Due to limitations of the kernel documentation framework and the existing layout of the source code the entire regulator API is documented here.


#### <a id="c-struct-pre_voltage_change_data"></a>`struct pre_voltage_change_data`

Data sent with PRE_VOLTAGE_CHANGE event

**Definition**

```c
struct pre_voltage_change_data {
    unsigned long old_uV;
    unsigned long min_uV;
    unsigned long max_uV;
};
```

**Members**

- `old_uV`: Current voltage before change.
- `min_uV`: Min voltage we'll change to.
- `max_uV`: Max voltage we'll change to.

#### <a id="c-struct-regulator_bulk_data"></a>`struct regulator_bulk_data`

Data used for bulk regulator operations.

**Definition**

```c
struct regulator_bulk_data {
    const char *supply;
    struct regulator *consumer;
    int init_load_uA;
};
```

**Members**

- `supply`: The name of the supply.  Initialised by the user before
  using the bulk regulator APIs.
- `consumer`: The regulator consumer for the supply.  This will be managed
  by the bulk API.
- `init_load_uA`: After getting the regulator, [`regulator_set_load()`](#c-regulator_set_load) will be
  called with this load.  Initialised by the user before
  using the bulk regulator APIs.

**Description**

The regulator APIs provide a series of `regulator_bulk_()` API calls as
a convenience to consumers which require multiple supplies.  This
structure is used to manage data for these calls.



#### <a id="c-struct-regulator_state"></a>`struct regulator_state`

regulator state during low power system states

**Definition**

```c
struct regulator_state {
    int uV;
    int min_uV;
    int max_uV;
    unsigned int mode;
    int enabled;
    bool changeable;
};
```

**Members**

- `uV`: Default operating voltage during suspend, it can be adjusted
  among \<min_uV, max_uV>.
- `min_uV`: Minimum suspend voltage may be set.
- `max_uV`: Maximum suspend voltage may be set.
- `mode`: Operating mode during suspend.
- `enabled`: operations during suspend.
  - DO_NOTHING_IN_SUSPEND
  - DISABLE_IN_SUSPEND
  - ENABLE_IN_SUSPEND
- `changeable`: Is this state can be switched between enabled/disabled,

**Description**

This describes a regulators state during a system wide low power
state.  One of enabled or disabled must be set for the
configuration to be applied.

#### <a id="c-struct-regulation_constraints"></a>`struct regulation_constraints`

regulator operating constraints.

**Definition**

```c
struct regulation_constraints {
    const char *name;
    int min_uV;
    int max_uV;
    int uV_offset;
    int min_uA;
    int max_uA;
    int ilim_uA;
    int pw_budget_mW;
    int system_load;
    u32 *max_spread;
    int max_uV_step;
    unsigned int valid_modes_mask;
    unsigned int valid_ops_mask;
    int input_uV;
    struct regulator_state state_disk;
    struct regulator_state state_mem;
    struct regulator_state state_standby;
    struct notification_limit over_curr_limits;
    struct notification_limit over_voltage_limits;
    struct notification_limit under_voltage_limits;
    struct notification_limit temp_limits;
    suspend_state_t initial_state;
    unsigned int initial_mode;
    unsigned int ramp_delay;
    unsigned int settling_time;
    unsigned int settling_time_up;
    unsigned int settling_time_down;
    unsigned int enable_time;
    unsigned int uv_less_critical_window_ms;
    unsigned int active_discharge;
    unsigned always_on:1;
    unsigned boot_on:1;
    unsigned apply_uV:1;
    unsigned ramp_disable:1;
    unsigned soft_start:1;
    unsigned pull_down:1;
    unsigned system_critical:1;
    unsigned over_current_protection:1;
    unsigned over_current_detection:1;
    unsigned over_voltage_detection:1;
    unsigned under_voltage_detection:1;
    unsigned over_temp_detection:1;
};
```

**Members**

- `name`: Descriptive name for the constraints, used for display purposes.
- `min_uV`: Smallest voltage consumers may set.
- `max_uV`: Largest voltage consumers may set.
- `uV_offset`: Offset applied to voltages from consumer to compensate for
  voltage drops.
- `min_uA`: Smallest current consumers may set.
- `max_uA`: Largest current consumers may set.
- `ilim_uA`: Maximum input current.
- `pw_budget_mW`: Power budget for the regulator in mW.
- `system_load`: Load that isn't captured by any consumer requests.
- `max_spread`: Max possible spread between coupled regulators
- `max_uV_step`: Max possible step change in voltage
- `valid_modes_mask`: Mask of modes which may be configured by consumers.
- `valid_ops_mask`: Operations which may be performed by consumers.
- `input_uV`: Input voltage for regulator when supplied by another regulator.
- `state_disk`: State for regulator when system is suspended in disk mode.
- `state_mem`: State for regulator when system is suspended in mem mode.
- `state_standby`: State for regulator when system is suspended in standby
  mode.
- `over_curr_limits`: Limits for acting on over current.
- `over_voltage_limits`: Limits for acting on over voltage.
- `under_voltage_limits`: Limits for acting on under voltage.
- `temp_limits`: Limits for acting on over temperature.
- `initial_state`: Suspend state to set by default.
- `initial_mode`: Mode to set at startup.
- `ramp_delay`: Time to settle down after voltage change (unit: uV/us)
- `settling_time`: Time to settle down after voltage change when voltage
  change is non-linear (unit: microseconds).
- `settling_time_up`: Time to settle down after voltage increase when voltage
  change is non-linear (unit: microseconds).
- `settling_time_down`: Time to settle down after voltage decrease when
  voltage change is non-linear (unit: microseconds).
- `enable_time`: Turn-on time of the rails (unit: microseconds)
- `uv_less_critical_window_ms`: Specifies the time window (in milliseconds)
  following a critical under-voltage (UV) event
  during which less critical actions can be
  safely carried out by the system (for example
  logging). After this time window more critical
  actions should be done (for example prevent
  HW damage).
- `active_discharge`: Enable/disable active discharge. The enum
  regulator_active_discharge values are used for
  initialisation.
- `always_on`: Set if the regulator should never be disabled.
- `boot_on`: Set if the regulator is enabled when the system is initially
  started.  If the regulator is not enabled by the hardware or
  bootloader then it will be enabled when the constraints are
  applied.
- `apply_uV`: Apply the voltage constraint when initialising.
- `ramp_disable`: Disable ramp delay when initialising or when setting voltage.
- `soft_start`: Enable soft start so that voltage ramps slowly.
- `pull_down`: Enable pull down when regulator is disabled.
- `system_critical`: Set if the regulator is critical to system stability or
  functionality.
- `over_current_protection`: Auto disable on over current event.
- `over_current_detection`: Configure over current limits.
- `over_voltage_detection`: Configure over voltage limits.
- `under_voltage_detection`: Configure under voltage limits.
- `over_temp_detection`: Configure over temperature limits.

**Description**

This struct describes regulator and board/machine specific constraints.

#### <a id="c-struct-regulator_consumer_supply"></a>`struct regulator_consumer_supply`

supply -> device mapping

**Definition**

```c
struct regulator_consumer_supply {
    const char *dev_name;
    const char *supply;
};
```

**Members**

- `dev_name`: Result of [`dev_name()`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-dev_name) for the consumer.
- `supply`: Name for the supply.

**Description**

This maps a supply name to a device. Use of dev_name allows support for
buses which make struct device available late such as I2C.

#### <a id="c-struct-regulator_init_data"></a>`struct regulator_init_data`

regulator platform initialisation data.

**Definition**

```c
struct regulator_init_data {
    const char *supply_regulator;
    struct regulation_constraints constraints;
    int num_consumer_supplies;
    struct regulator_consumer_supply *consumer_supplies;
    void *driver_data;
};
```

**Members**

- `supply_regulator`: Parent regulator.  Specified using the regulator name
  as it appears in the name field in sysfs, which can
  be explicitly set using the constraints field 'name'.
- `constraints`: Constraints.  These must be specified for the regulator to
  be usable.
- `num_consumer_supplies`: Number of consumer device supplies.
- `consumer_supplies`: Consumer device supply configuration.
- `driver_data`: Data passed to regulator_init.

**Description**

Initialisation constraints, our supply and consumers supplies.



#### <a id="c-struct-regulator_ops"></a>`struct regulator_ops`

regulator operations.

**Definition**

```c
struct regulator_ops {
    int (*list_voltage) (struct regulator_dev *, unsigned selector);
    int (*set_voltage) (struct regulator_dev *, int min_uV, int max_uV, unsigned *selector);
    int (*map_voltage)(struct regulator_dev *, int min_uV, int max_uV);
    int (*set_voltage_sel) (struct regulator_dev *, unsigned selector);
    int (*get_voltage) (struct regulator_dev *);
    int (*get_voltage_sel) (struct regulator_dev *);
    int (*set_current_limit) (struct regulator_dev *, int min_uA, int max_uA);
    int (*get_current_limit) (struct regulator_dev *);
    int (*set_input_current_limit) (struct regulator_dev *, int lim_uA);
    int (*set_over_current_protection)(struct regulator_dev *, int lim_uA, int severity, bool enable);
    int (*set_over_voltage_protection)(struct regulator_dev *, int lim_uV, int severity, bool enable);
    int (*set_under_voltage_protection)(struct regulator_dev *, int lim_uV, int severity, bool enable);
    int (*set_thermal_protection)(struct regulator_dev *, int lim, int severity, bool enable);
    int (*set_active_discharge)(struct regulator_dev *, bool enable);
    int (*enable) (struct regulator_dev *);
    int (*disable) (struct regulator_dev *);
    int (*is_enabled) (struct regulator_dev *);
    int (*set_mode) (struct regulator_dev *, unsigned int mode);
    unsigned int (*get_mode) (struct regulator_dev *);
    int (*get_error_flags)(struct regulator_dev *, unsigned int *flags);
    int (*enable_time) (struct regulator_dev *);
    int (*set_ramp_delay) (struct regulator_dev *, int ramp_delay);
    int (*set_voltage_time) (struct regulator_dev *, int old_uV, int new_uV);
    int (*set_voltage_time_sel) (struct regulator_dev *, unsigned int old_selector, unsigned int new_selector);
    int (*set_soft_start) (struct regulator_dev *);
    int (*get_status)(struct regulator_dev *);
    unsigned int (*get_optimum_mode) (struct regulator_dev *, int input_uV, int output_uV, int load_uA);
    int (*set_load)(struct regulator_dev *, int load_uA);
    int (*set_bypass)(struct regulator_dev *dev, bool enable);
    int (*get_bypass)(struct regulator_dev *dev, bool *enable);
    int (*set_suspend_voltage) (struct regulator_dev *, int uV);
    int (*set_suspend_enable) (struct regulator_dev *);
    int (*set_suspend_disable) (struct regulator_dev *);
    int (*set_suspend_mode) (struct regulator_dev *, unsigned int mode);
    int (*resume)(struct regulator_dev *rdev);
    int (*set_pull_down) (struct regulator_dev *);
};
```

**Members**

- `list_voltage`: Return one of the supported voltages, in microvolts; zero
  if the selector indicates a voltage that is unusable on this system;
  or negative errno.  Selectors range from zero to one less than
  regulator_desc.n_voltages.  Voltages may be reported in any order.
- `set_voltage`: Set the voltage for the regulator within the range specified.
  The driver should select the voltage closest to min_uV.
- `map_voltage`: Convert a voltage into a selector
- `set_voltage_sel`: Set the voltage for the regulator using the specified
  selector.
- `get_voltage`: Return the currently configured voltage for the regulator;
  return -ENOTRECOVERABLE if regulator can't be read at
  bootup and hasn't been set yet.
- `get_voltage_sel`: Return the currently configured voltage selector for the
  regulator; return -ENOTRECOVERABLE if regulator can't
  be read at bootup and hasn't been set yet.
- `set_current_limit`: Configure a limit for a current-limited regulator.
  The driver should select the current closest to max_uA.
- `get_current_limit`: Get the configured limit for a current-limited regulator.
- `set_input_current_limit`: Configure an input limit.
- `set_over_current_protection`: Support enabling of and setting limits for over
  current situation detection. Detection can be configured for three
  levels of severity.
- `set_over_voltage_protection`: Support enabling of and setting limits for over
  voltage situation detection. Detection can be configured for same
  severities as over current protection. Units of uV.
- `set_under_voltage_protection`: Support enabling of and setting limits for
  under voltage situation detection. Detection can be configured for same
  severities as over current protection. Units of uV.
- `set_thermal_protection`: Support enabling of and setting limits for over
  temperature situation detection.Detection can be configured for same
  severities as over current protection. Units of degree Kelvin.
- `set_active_discharge`: Set active discharge enable/disable of regulators.
- `enable`: Configure the regulator as enabled.
- `disable`: Configure the regulator as disabled.
- `is_enabled`: Return 1 if the regulator is enabled, 0 if not.
  May also return negative errno.
- `set_mode`: Set the configured operating mode for the regulator.
- `get_mode`: Get the configured operating mode for the regulator.
- `get_error_flags`: Get the current error(s) for the regulator.
- `enable_time`: Time taken for the regulator voltage output voltage to
  stabilise after being enabled, in microseconds.
- `set_ramp_delay`: Set the ramp delay for the regulator. The driver should
  select ramp delay equal to or less than(closest) ramp_delay.
- `set_voltage_time`: Time taken for the regulator voltage output voltage
  to stabilise after being set to a new value, in microseconds.
  The function receives the from and to voltage as input, it
  should return the worst case.
- `set_voltage_time_sel`: Time taken for the regulator voltage output voltage
  to stabilise after being set to a new value, in microseconds.
  The function receives the from and to voltage selector as
  input, it should return the worst case.
- `set_soft_start`: Enable soft start for the regulator.
- `get_status`: Return actual (not as-configured) status of regulator, as a
  REGULATOR_STATUS value (or negative errno)
- `get_optimum_mode`: Get the most efficient operating mode for the regulator
  when running with the specified parameters.
- `set_load`: Set the load for the regulator.
- `set_bypass`: Set the regulator in bypass mode.
- `get_bypass`: Get the regulator bypass mode state.
- `set_suspend_voltage`: Set the voltage for the regulator when the system
  is suspended.
- `set_suspend_enable`: Mark the regulator as enabled when the system is
  suspended.
- `set_suspend_disable`: Mark the regulator as disabled when the system is
  suspended.
- `set_suspend_mode`: Set the operating mode for the regulator when the
  system is suspended.
- `resume`: Resume operation of suspended regulator.
- `set_pull_down`: Configure the regulator to pull down when the regulator
  is disabled.

**Description**

- REGULATOR_SEVERITY_PROT should automatically shut down the regulator(s).

- REGULATOR_SEVERITY_ERR should indicate that over-current situation is
  caused by an unrecoverable error but HW does not perform
  automatic shut down.

- REGULATOR_SEVERITY_WARN should indicate situation where hardware is
  still believed to not be damaged but that a board sepcific
  recovery action is needed. If lim_uA is 0 the limit should not
  be changed but the detection should just be enabled/disabled as
  is requested.

This struct describes regulator operations which can be implemented by
regulator chip drivers.

#### <a id="c-struct-regulator_desc"></a>`struct regulator_desc`

Static regulator descriptor

**Definition**

```c
struct regulator_desc {
    const char *name;
    const char *supply_name;
    const char *of_match;
    bool of_match_full_name;
    const char *regulators_node;
    int (*of_parse_cb)(struct device_node *, const struct regulator_desc *, struct regulator_config *);
    int (*init_cb)(struct regulator_dev *, struct regulator_config *);
    int id;
    unsigned int continuous_voltage_range:1;
    unsigned n_voltages;
    unsigned int n_current_limits;
    const struct regulator_ops *ops;
    int irq;
    enum regulator_type type;
    struct module *owner;
    unsigned int min_uV;
    unsigned int uV_step;
    unsigned int linear_min_sel;
    int fixed_uV;
    unsigned int ramp_delay;
    int min_dropout_uV;
    const struct linear_range *linear_ranges;
    const unsigned int *linear_range_selectors_bitfield;
    int n_linear_ranges;
    const unsigned int *volt_table;
    const unsigned int *curr_table;
    unsigned int vsel_range_reg;
    unsigned int vsel_range_mask;
    bool range_applied_by_vsel;
    unsigned int vsel_reg;
    unsigned int vsel_mask;
    unsigned int vsel_step;
    unsigned int csel_reg;
    unsigned int csel_mask;
    unsigned int apply_reg;
    unsigned int apply_bit;
    unsigned int enable_reg;
    unsigned int enable_mask;
    unsigned int enable_val;
    unsigned int disable_val;
    bool enable_is_inverted;
    unsigned int bypass_reg;
    unsigned int bypass_mask;
    unsigned int bypass_val_on;
    unsigned int bypass_val_off;
    unsigned int active_discharge_on;
    unsigned int active_discharge_off;
    unsigned int active_discharge_mask;
    unsigned int active_discharge_reg;
    unsigned int soft_start_reg;
    unsigned int soft_start_mask;
    unsigned int soft_start_val_on;
    unsigned int pull_down_reg;
    unsigned int pull_down_mask;
    unsigned int pull_down_val_on;
    unsigned int ramp_reg;
    unsigned int ramp_mask;
    const unsigned int *ramp_delay_table;
    unsigned int n_ramp_values;
    unsigned int enable_time;
    unsigned int off_on_delay;
    unsigned int poll_enabled_time;
    unsigned int (*of_map_mode)(unsigned int mode);
};
```

**Members**

- `name`: Identifying name for the regulator.
- `supply_name`: Identifying the regulator supply
- `of_match`: Name used to identify regulator in DT.
- `of_match_full_name`: A flag to indicate that the of_match string, if
  present, should be matched against the node full_name.
- `regulators_node`: Name of node containing regulator definitions in DT.
- `of_parse_cb`: Optional callback called only if of_match is present.
  Will be called for each regulator parsed from DT, during
  init_data parsing.
  The regulator_config passed as argument to the callback will
  be a copy of config passed to regulator_register, valid only
  for this particular call. Callback may freely change the
  config but it cannot store it for later usage.
  Callback should return 0 on success or negative ERRNO
  indicating failure.
- `init_cb`: Optional callback called after the parsing of init_data.
  Allows the regulator to perform runtime init if necessary,
  such as synching the regulator and the parsed constraints.
  Callback should return 0 on success or negative ERRNO
  indicating failure.
- `id`: Numerical identifier for the regulator.
- `continuous_voltage_range`: Indicates if the regulator can set any
  voltage within constrains range.
- `n_voltages`: Number of selectors available for ops.`list_voltage()`.
- `n_current_limits`: Number of selectors available for current limits
- `ops`: Regulator operations table.
- `irq`: Interrupt number for the regulator.
- `type`: Indicates if the regulator is a voltage or current regulator.
- `owner`: Module providing the regulator, used for refcounting.
- `min_uV`: Voltage given by the lowest selector (if linear mapping)
- `uV_step`: Voltage increase with each selector (if linear mapping)
- `linear_min_sel`: Minimal selector for starting linear mapping
- `fixed_uV`: Fixed voltage of rails.
- `ramp_delay`: Time to settle down after voltage change (unit: uV/us)
- `min_dropout_uV`: The minimum dropout voltage this regulator can handle
- `linear_ranges`: A constant table of possible voltage ranges.
- `linear_range_selectors_bitfield`: A constant table of voltage range
  selectors as bitfield values. If
  pickable ranges are used each range
  must have corresponding selector here.
- `n_linear_ranges`: Number of entries in the **linear_ranges** (and in
  linear_range_selectors_bitfield if used) table(s).
- `volt_table`: Voltage mapping table (if table based mapping)
- `curr_table`: Current limit mapping table (if table based mapping)
- `vsel_range_reg`: Register for range selector when using pickable ranges
  and `regulator_map_*_voltage_*_pickable` functions.
- `vsel_range_mask`: Mask for register bitfield used for range selector
- `range_applied_by_vsel`: A flag to indicate that changes to vsel_range_reg
  are only effective after vsel_reg is written
- `vsel_reg`: Register for selector when using `regulator_map_*_voltage_*`
- `vsel_mask`: Mask for register bitfield used for selector
- `vsel_step`: Specify the resolution of selector stepping when setting
  voltage. If 0, then no stepping is done (requested selector is
  set directly), if >0 then the regulator API will ramp the
  voltage up/down gradually each time increasing/decreasing the
  selector by the specified step value.
- `csel_reg`: Register for current limit selector using regmap set_current_limit
- `csel_mask`: Mask for register bitfield used for current limit selector
- `apply_reg`: Register for initiate voltage change on the output when
  using regulator_set_voltage_sel_regmap
- `apply_bit`: Register bitfield used for initiate voltage change on the
  output when using regulator_set_voltage_sel_regmap
- `enable_reg`: Register for control when using regmap enable/disable ops
- `enable_mask`: Mask for control when using regmap enable/disable ops
- `enable_val`: Enabling value for control when using regmap enable/disable ops
- `disable_val`: Disabling value for control when using regmap enable/disable ops
- `enable_is_inverted`: A flag to indicate set enable_mask bits to disable
  when using regulator_enable_regmap and friends APIs.
- `bypass_reg`: Register for control when using regmap set_bypass
- `bypass_mask`: Mask for control when using regmap set_bypass
- `bypass_val_on`: Enabling value for control when using regmap set_bypass
- `bypass_val_off`: Disabling value for control when using regmap set_bypass
- `active_discharge_on`: Disabling value for control when using regmap
  set_active_discharge
- `active_discharge_off`: Enabling value for control when using regmap
  set_active_discharge
- `active_discharge_mask`: Mask for control when using regmap
  set_active_discharge
- `active_discharge_reg`: Register for control when using regmap
  set_active_discharge
- `soft_start_reg`: Register for control when using regmap set_soft_start
- `soft_start_mask`: Mask for control when using regmap set_soft_start
- `soft_start_val_on`: Enabling value for control when using regmap
  set_soft_start
- `pull_down_reg`: Register for control when using regmap set_pull_down
- `pull_down_mask`: Mask for control when using regmap set_pull_down
- `pull_down_val_on`: Enabling value for control when using regmap
  set_pull_down
- `ramp_reg`: Register for controlling the regulator ramp-rate.
- `ramp_mask`: Bitmask for the ramp-rate control register.
- `ramp_delay_table`: Table for mapping the regulator ramp-rate values. Values
  should be given in units of V/S (uV/uS). See the
  `regulator_set_ramp_delay_regmap()`.
- `n_ramp_values`: number of elements at **ramp_delay_table**.
- `enable_time`: Time taken for initial enable of regulator (in uS).
- `off_on_delay`: guard time (in uS), before re-enabling a regulator
- `poll_enabled_time`: The polling interval (in uS) to use while checking that
  the regulator was actually enabled. Max upto enable_time.
- `of_map_mode`: Maps a hardware mode defined in a DeviceTree to a standard mode

**Description**

Each regulator registered with the core is described with a
structure of this type and a struct regulator_config.  This
structure contains the non-varying parts of the regulator
description.

#### <a id="c-struct-regulator_config"></a>`struct regulator_config`

Dynamic regulator descriptor

**Definition**

```c
struct regulator_config {
    struct device *dev;
    const struct regulator_init_data *init_data;
    void *driver_data;
    struct device_node *of_node;
    struct regmap *regmap;
    struct gpio_desc *ena_gpiod;
};
```

**Members**

- `dev`: struct device for the regulator
- `init_data`: platform provided init data, passed through by driver
- `driver_data`: private regulator data
- `of_node`: OpenFirmware node to parse for device tree bindings (may be
  NULL).
- `regmap`: regmap to use for core regmap helpers if `dev_get_regmap()` is
  insufficient.
- `ena_gpiod`: GPIO controlling regulator enable.

**Description**

Each regulator registered with the core is described with a
structure of this type and a struct regulator_desc.  This structure
contains the runtime variable parts of the regulator description.

#### <a id="c-struct-regulator_err_state"></a>`struct regulator_err_state`

regulator error/notification status

**Definition**

```c
struct regulator_err_state {
    struct regulator_dev *rdev;
    unsigned long notifs;
    unsigned long errors;
    int possible_errs;
};
```

**Members**

- `rdev`: Regulator which status the struct indicates.
- `notifs`: Events which have occurred on the regulator.
- `errors`: Errors which are active on the regulator.
- `possible_errs`: Errors which can be signaled (by given IRQ).

#### <a id="c-struct-regulator_irq_data"></a>`struct regulator_irq_data`

regulator error/notification status data

**Definition**

```c
struct regulator_irq_data {
    struct regulator_err_state *states;
    int num_states;
    void *data;
    long opaque;
};
```

**Members**

- `states`: Status structs for each of the associated regulators.
- `num_states`: Amount of associated regulators.
- `data`: Driver data pointer given at regulator_irq_desc.
- `opaque`: Value storage for IC driver. Core does not update this. ICs
  may want to store status register value here at map_event and
  compare contents at 'renable' callback to see if new problems
  have been added to status. If that is the case it may be
  desirable to return REGULATOR_ERROR_CLEARED and not
  REGULATOR_ERROR_ON to allow IRQ fire again and to generate
  notifications also for the new issues.

**Description**

This structure is passed to 'map_event' and 'renable' callbacks for
reporting regulator status to core.

#### <a id="c-struct-regulator_irq_desc"></a>`struct regulator_irq_desc`

notification sender for IRQ based events.

**Definition**

```c
struct regulator_irq_desc {
    const char *name;
    int fatal_cnt;
    int reread_ms;
    int irq_off_ms;
    bool skip_off;
    bool high_prio;
    void *data;
    int (*die)(struct regulator_irq_data *rid);
    int (*map_event)(int irq, struct regulator_irq_data *rid, unsigned long *dev_mask);
    int (*renable)(struct regulator_irq_data *rid);
};
```

**Members**

- `name`: The visible name for the IRQ
- `fatal_cnt`: If this IRQ is used to signal HW damaging condition it may be
  best to shut-down regulator(s) or reboot the SOC if error
  handling is repeatedly failing. If fatal_cnt is given the IRQ
  handling is aborted if it fails for fatal_cnt times and `die()`
  callback (if populated) is called. If `die()` is not populated
  poweroff for the system is attempted in order to prevent any
  further damage.
- `reread_ms`: The time which is waited before attempting to re-read status
  at the worker if IC reading fails. Immediate re-read is done
  if time is not specified.
- `irq_off_ms`: The time which IRQ is kept disabled before re-evaluating the
  status for devices which keep IRQ disabled for duration of the
  error. If this is not given the IRQ is left enabled and renable
  is not called.
- `skip_off`: If set to true the IRQ handler will attempt to check if any of
  the associated regulators are enabled prior to taking other
  actions. If no regulators are enabled and this is set to true
  a spurious IRQ is assumed and IRQ_NONE is returned.
- `high_prio`: Boolean to indicate that high priority WQ should be used.
- `data`: Driver private data pointer which will be passed as such to
  the renable, map_event and die callbacks in regulator_irq_data.
- `die`: Protection callback. If IC status reading or recovery actions
  fail fatal_cnt times this callback is called or system is
  powered off. This callback should implement a final protection
  attempt like disabling the regulator. If protection succeeded
  `die()` may return 0. If anything else is returned the core
  assumes final protection failed and attempts to perform a
  poweroff as a last resort.
- `map_event`: Driver callback to map IRQ status into regulator devices with
  events / errors. NOTE: callback MUST initialize both the
  errors and notifs for all rdevs which it signals having
  active events as core does not clean the map data.
  REGULATOR_FAILED_RETRY can be returned to indicate that the
  status reading from IC failed. If this is repeated for
  fatal_cnt times the core will call `die()` callback or power-off
  the system as a last resort to protect the HW.
- `renable`: Optional callback to check status (if HW supports that) before
  re-enabling IRQ. If implemented this should clear the error
  flags so that errors fetched by [`regulator_get_error_flags()`](#c-regulator_get_error_flags)
  are updated. If callback is not implemented then errors are
  assumed to be cleared and IRQ is re-enabled.
  REGULATOR_FAILED_RETRY can be returned to
  indicate that the status reading from IC failed. If this is
  repeated for 'fatal_cnt' times the core will call `die()`
  callback or if `die()` is not populated then attempt to power-off
  the system as a last resort to protect the HW.
  Returning zero indicates that the problem in HW has been solved
  and IRQ will be re-enabled. Returning REGULATOR_ERROR_ON
  indicates the error condition is still active and keeps IRQ
  disabled. Please note that returning REGULATOR_ERROR_ON does
  not retrigger evaluating what events are active or resending
  notifications. If this is needed you probably want to return
  zero and allow IRQ to retrigger causing events to be
  re-evaluated and re-sent.

**Description**

This structure is used for registering regulator IRQ notification helper.



#### <a id="c-regulator_get"></a>`regulator_get()`

```c
struct regulator * regulator_get(struct device *dev, const char *id)
```

lookup and obtain a reference to a regulator.

**Parameters**

- `struct device *dev`: device for regulator "consumer"
- `const char *id`: Supply name or regulator ID.

**Description**

Use of supply names configured via `set_consumer_device_supply()` is
strongly encouraged.  It is recommended that the supply name used
should match the name used for the supply and/or the relevant
device pins in the datasheet.

**Return**

Pointer to a `struct regulator` corresponding to the regulator
producer, or an [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR) encoded negative error number.

#### <a id="c-regulator_get_exclusive"></a>`regulator_get_exclusive()`

```c
struct regulator * regulator_get_exclusive(struct device *dev, const char *id)
```

obtain exclusive access to a regulator.

**Parameters**

- `struct device *dev`: device for regulator "consumer"
- `const char *id`: Supply name or regulator ID.

**Description**

Other consumers will be unable to obtain this regulator while this
reference is held and the use count for the regulator will be
initialised to reflect the current state of the regulator.

This is intended for use by consumers which cannot tolerate shared
use of the regulator such as those which need to force the
regulator off for correct operation of the hardware they are
controlling.

Use of supply names configured via `set_consumer_device_supply()` is
strongly encouraged.  It is recommended that the supply name used
should match the name used for the supply and/or the relevant
device pins in the datasheet.

**Return**

Pointer to a `struct regulator` corresponding to the regulator
producer, or an [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR) encoded negative error number.

#### <a id="c-regulator_get_optional"></a>`regulator_get_optional()`

```c
struct regulator * regulator_get_optional(struct device *dev, const char *id)
```

obtain optional access to a regulator.

**Parameters**

- `struct device *dev`: device for regulator "consumer"
- `const char *id`: Supply name or regulator ID.

**Description**

This is intended for use by consumers for devices which can have
some supplies unconnected in normal use, such as some MMC devices.
It can allow the regulator core to provide stub supplies for other
supplies requested using normal [`regulator_get()`](#c-regulator_get) calls without
disrupting the operation of drivers that can handle absent
supplies.

Use of supply names configured via `set_consumer_device_supply()` is
strongly encouraged.  It is recommended that the supply name used
should match the name used for the supply and/or the relevant
device pins in the datasheet.

**Return**

Pointer to a `struct regulator` corresponding to the regulator
producer, or an [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR) encoded negative error number.

#### <a id="c-regulator_put"></a>`regulator_put()`

```c
void regulator_put(struct regulator *regulator)
```

"free" the regulator source

**Parameters**

- `struct regulator *regulator`: regulator source

**Note**

drivers must ensure that all regulator_enable calls made on this
regulator source are balanced by regulator_disable calls prior to calling
this function.

#### <a id="c-regulator_register_supply_alias"></a>`regulator_register_supply_alias()`

```c
int regulator_register_supply_alias(struct device *dev, const char *id, struct device *alias_dev, const char *alias_id)
```

Provide device alias for supply lookup

**Parameters**

- `struct device *dev`: device that will be given as the regulator "consumer"
- `const char *id`: Supply name or regulator ID
- `struct device *alias_dev`: device that should be used to lookup the supply
- `const char *alias_id`: Supply name or regulator ID that should be used to lookup the
  supply

**Description**

All lookups for id on dev will instead be conducted for alias_id on
alias_dev.

**Return**

0 on success or a negative error number on failure.

#### <a id="c-regulator_unregister_supply_alias"></a>`regulator_unregister_supply_alias()`

```c
void regulator_unregister_supply_alias(struct device *dev, const char *id)
```

Remove device alias

**Parameters**

- `struct device *dev`: device that will be given as the regulator "consumer"
- `const char *id`: Supply name or regulator ID

**Description**

Remove a lookup alias if one exists for id on dev.

#### <a id="c-regulator_bulk_register_supply_alias"></a>`regulator_bulk_register_supply_alias()`

```c
int regulator_bulk_register_supply_alias(struct device *dev, const char *const *id, struct device *alias_dev, const char *const *alias_id, int num_id)
```

register multiple aliases

**Parameters**

- `struct device *dev`: device that will be given as the regulator "consumer"
- `const char *const *id`: List of supply names or regulator IDs
- `struct device *alias_dev`: device that should be used to lookup the supply
- `const char *const *alias_id`: List of supply names or regulator IDs that should be used to
  lookup the supply
- `int num_id`: Number of aliases to register

**Description**

This helper function allows drivers to register several supply
aliases in one operation.  If any of the aliases cannot be
registered any aliases that were registered will be removed
before returning to the caller.

**Return**

0 on success or a negative error number on failure.

#### <a id="c-regulator_bulk_unregister_supply_alias"></a>`regulator_bulk_unregister_supply_alias()`

```c
void regulator_bulk_unregister_supply_alias(struct device *dev, const char *const *id, int num_id)
```

unregister multiple aliases

**Parameters**

- `struct device *dev`: device that will be given as the regulator "consumer"
- `const char *const *id`: List of supply names or regulator IDs
- `int num_id`: Number of aliases to unregister

**Description**

This helper function allows drivers to unregister several supply
aliases in one operation.

#### <a id="c-regulator_enable"></a>`regulator_enable()`

```c
int regulator_enable(struct regulator *regulator)
```

enable regulator output

**Parameters**

- `struct regulator *regulator`: regulator source

**Description**

Request that the regulator be enabled with the regulator output at
the predefined voltage or current value.  Calls to [`regulator_enable()`](#c-regulator_enable)
must be balanced with calls to [`regulator_disable()`](#c-regulator_disable).

**NOTE**

the output value can be set by other drivers, boot loader or may be
hardwired in the regulator.

**Return**

0 on success or a negative error number on failure.

#### <a id="c-regulator_disable"></a>`regulator_disable()`

```c
int regulator_disable(struct regulator *regulator)
```

disable regulator output

**Parameters**

- `struct regulator *regulator`: regulator source

**Description**

Disable the regulator output voltage or current.  Calls to
[`regulator_enable()`](#c-regulator_enable) must be balanced with calls to
[`regulator_disable()`](#c-regulator_disable).

**NOTE**

this will only disable the regulator output if no other consumer
devices have it enabled, the regulator device supports disabling and
machine constraints permit this operation.

**Return**

0 on success or a negative error number on failure.

#### <a id="c-regulator_force_disable"></a>`regulator_force_disable()`

```c
int regulator_force_disable(struct regulator *regulator)
```

force disable regulator output

**Parameters**

- `struct regulator *regulator`: regulator source

**Description**

Forcibly disable the regulator output voltage or current.

**NOTE**

this *will* disable the regulator output even if other consumer
devices have it enabled. This should be used for situations when device
damage will likely occur if the regulator is not disabled (e.g. over temp).

**Return**

0 on success or a negative error number on failure.

#### <a id="c-regulator_disable_deferred"></a>`regulator_disable_deferred()`

```c
int regulator_disable_deferred(struct regulator *regulator, int ms)
```

disable regulator output with delay

**Parameters**

- `struct regulator *regulator`: regulator source
- `int ms`: milliseconds until the regulator is disabled

**Description**

Execute [`regulator_disable()`](#c-regulator_disable) on the regulator after a delay.  This
is intended for use with devices that require some time to quiesce.

**NOTE**

this will only disable the regulator output if no other consumer
devices have it enabled, the regulator device supports disabling and
machine constraints permit this operation.

**Return**

0 on success or a negative error number on failure.

#### <a id="c-regulator_is_enabled"></a>`regulator_is_enabled()`

```c
int regulator_is_enabled(struct regulator *regulator)
```

is the regulator output enabled

**Parameters**

- `struct regulator *regulator`: regulator source

**Description**

Note that the device backing this regulator handle can have multiple
users, so it might be enabled even if [`regulator_enable()`](#c-regulator_enable) was never
called for this particular source.

**Return**

Positive if the regulator driver backing the source/client
has requested that the device be enabled, zero if it hasn't,
else a negative error number.

#### <a id="c-regulator_count_voltages"></a>`regulator_count_voltages()`

```c
int regulator_count_voltages(struct regulator *regulator)
```

count [`regulator_list_voltage()`](#c-regulator_list_voltage) selectors

**Parameters**

- `struct regulator *regulator`: regulator source

**Return**

Number of selectors for **regulator**, or negative error number.

**Description**

Selectors are numbered starting at zero, and typically correspond to
bitfields in hardware registers.

#### <a id="c-regulator_list_voltage"></a>`regulator_list_voltage()`

```c
int regulator_list_voltage(struct regulator *regulator, unsigned selector)
```

enumerate supported voltages

**Parameters**

- `struct regulator *regulator`: regulator source
- `unsigned selector`: identify voltage to list

**Context**

can sleep

**Return**

Voltage for **selector** that can be passed to [`regulator_set_voltage()`](#c-regulator_set_voltage),
0 if **selector** can't be used on this system, or a negative error
number on failure.

#### <a id="c-regulator_get_regmap"></a>`regulator_get_regmap()`

```c
struct regmap * regulator_get_regmap(struct regulator *regulator)
```

get the regulator's register map

**Parameters**

- `struct regulator *regulator`: regulator source

**Return**

Pointer to the `struct regmap` for **regulator**, or [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR)
encoded -`EOPNOTSUPP` if **regulator** doesn't use regmap.

#### <a id="c-regulator_get_hardware_vsel_register"></a>`regulator_get_hardware_vsel_register()`

```c
int regulator_get_hardware_vsel_register(struct regulator *regulator, unsigned *vsel_reg, unsigned *vsel_mask)
```

get the HW voltage selector register

**Parameters**

- `struct regulator *regulator`: regulator source
- `unsigned *vsel_reg`: voltage selector register, output parameter
- `unsigned *vsel_mask`: mask for voltage selector bitfield, output parameter

**Description**

Returns the hardware register offset and bitmask used for setting the
regulator voltage. This might be useful when configuring voltage-scaling
hardware or firmware that can make I2C requests behind the kernel's back,
for example.

On success, the output parameters **vsel_reg** and **vsel_mask** are filled in
and 0 is returned, otherwise a negative error number is returned.

**Return**

0 on success, or -`EOPNOTSUPP` if the regulator does not support
voltage selectors.

#### <a id="c-regulator_list_hardware_vsel"></a>`regulator_list_hardware_vsel()`

```c
int regulator_list_hardware_vsel(struct regulator *regulator, unsigned selector)
```

get the HW-specific register value for a selector

**Parameters**

- `struct regulator *regulator`: regulator source
- `unsigned selector`: identify voltage to list

**Description**

Converts the selector to a hardware-specific voltage selector that can be
directly written to the regulator registers. The address of the voltage
register can be determined by calling **regulator_get_hardware_vsel_register**.

**Return**

0 on success, -`EINVAL` if the selector is outside the supported
range, or -`EOPNOTSUPP` if the regulator does not support voltage
selectors.

#### <a id="c-regulator_hardware_enable"></a>`regulator_hardware_enable()`

```c
int regulator_hardware_enable(struct regulator *regulator, bool enable)
```

access the HW for enable/disable regulator

**Parameters**

- `struct regulator *regulator`: regulator source
- `bool enable`: true for enable, false for disable

**Description**

Request that the regulator be enabled/disabled with the regulator output at
the predefined voltage or current value.

**Return**

0 on success or a negative error number on failure.

#### <a id="c-regulator_get_linear_step"></a>`regulator_get_linear_step()`

```c
unsigned int regulator_get_linear_step(struct regulator *regulator)
```

return the voltage step size between VSEL values

**Parameters**

- `struct regulator *regulator`: regulator source

**Return**

The voltage step size between VSEL values for linear regulators,
or 0 if the regulator isn't a linear regulator.

#### <a id="c-regulator_is_supported_voltage"></a>`regulator_is_supported_voltage()`

```c
int regulator_is_supported_voltage(struct regulator *regulator, int min_uV, int max_uV)
```

check if a voltage range can be supported

**Parameters**

- `struct regulator *regulator`: Regulator to check.
- `int min_uV`: Minimum required voltage in uV.
- `int max_uV`: Maximum required voltage in uV.

**Return**

1 if the voltage range is supported, 0 if not, or a negative error
number if **regulator**'s voltage can't be changed and voltage readback
failed.

#### <a id="c-regulator_set_voltage"></a>`regulator_set_voltage()`

```c
int regulator_set_voltage(struct regulator *regulator, int min_uV, int max_uV)
```

set regulator output voltage

**Parameters**

- `struct regulator *regulator`: regulator source
- `int min_uV`: Minimum required voltage in uV
- `int max_uV`: Maximum acceptable voltage in uV

**Description**

Sets a voltage regulator to the desired output voltage. This can be set
during any regulator state. IOW, regulator can be disabled or enabled.

If the regulator is enabled then the voltage will change to the new value
immediately otherwise if the regulator is disabled the regulator will
output at the new voltage when enabled.

**NOTE**

If the regulator is shared between several devices then the lowest
request voltage that meets the system constraints will be used.
Regulator system constraints must be set for this regulator before
calling this function otherwise this call will fail.

**Return**

0 on success or a negative error number on failure.

#### <a id="c-regulator_set_voltage_time"></a>`regulator_set_voltage_time()`

```c
int regulator_set_voltage_time(struct regulator *regulator, int old_uV, int new_uV)
```

get raise/fall time

**Parameters**

- `struct regulator *regulator`: regulator source
- `int old_uV`: starting voltage in microvolts
- `int new_uV`: target voltage in microvolts

**Description**

Provided with the starting and ending voltage, this function attempts to
calculate the time in microseconds required to rise or fall to this new
voltage.

**Return**

ramp time in microseconds, or a negative error number if calculation failed.

#### <a id="c-regulator_set_voltage_time_sel"></a>`regulator_set_voltage_time_sel()`

```c
int regulator_set_voltage_time_sel(struct regulator_dev *rdev, unsigned int old_selector, unsigned int new_selector)
```

get raise/fall time

**Parameters**

- `struct regulator_dev *rdev`: regulator source device
- `unsigned int old_selector`: selector for starting voltage
- `unsigned int new_selector`: selector for target voltage

**Description**

Provided with the starting and target voltage selectors, this function
returns time in microseconds required to rise or fall to this new voltage

Drivers providing ramp_delay in regulation_constraints can use this as their
`set_voltage_time_sel()` operation.

**Return**

ramp time in microseconds, or a negative error number if calculation failed.

#### <a id="c-regulator_sync_voltage"></a>`regulator_sync_voltage()`

```c
int regulator_sync_voltage(struct regulator *regulator)
```

re-apply last regulator output voltage

**Parameters**

- `struct regulator *regulator`: regulator source

**Description**

Re-apply the last configured voltage.  This is intended to be used
where some external control source the consumer is cooperating with
has caused the configured voltage to change.

**Return**

0 on success or a negative error number on failure.

#### <a id="c-regulator_get_voltage"></a>`regulator_get_voltage()`

```c
int regulator_get_voltage(struct regulator *regulator)
```

get regulator output voltage

**Parameters**

- `struct regulator *regulator`: regulator source

**Return**

Current regulator voltage in uV, or a negative error number on failure.

**NOTE**

If the regulator is disabled it will return the voltage value. This
function should not be used to determine regulator state.

#### <a id="c-regulator_set_current_limit"></a>`regulator_set_current_limit()`

```c
int regulator_set_current_limit(struct regulator *regulator, int min_uA, int max_uA)
```

set regulator output current limit

**Parameters**

- `struct regulator *regulator`: regulator source
- `int min_uA`: Minimum supported current in uA
- `int max_uA`: Maximum supported current in uA

**Description**

Sets current sink to the desired output current. This can be set during
any regulator state. IOW, regulator can be disabled or enabled.

If the regulator is enabled then the current will change to the new value
immediately otherwise if the regulator is disabled the regulator will
output at the new current when enabled.

**NOTE**

Regulator system constraints must be set for this regulator before
calling this function otherwise this call will fail.

**Return**

0 on success or a negative error number on failure.

#### <a id="c-regulator_get_current_limit"></a>`regulator_get_current_limit()`

```c
int regulator_get_current_limit(struct regulator *regulator)
```

get regulator output current

**Parameters**

- `struct regulator *regulator`: regulator source

**Return**

Current supplied by the specified current sink in uA,
or a negative error number on failure.

**NOTE**

If the regulator is disabled it will return the current value. This
function should not be used to determine regulator state.

#### <a id="c-regulator_get_unclaimed_power_budget"></a>`regulator_get_unclaimed_power_budget()`

```c
int regulator_get_unclaimed_power_budget(struct regulator *regulator)
```

get regulator unclaimed power budget

**Parameters**

- `struct regulator *regulator`: regulator source

**Return**

Unclaimed power budget of the regulator in mW.

#### <a id="c-regulator_request_power_budget"></a>`regulator_request_power_budget()`

```c
int regulator_request_power_budget(struct regulator *regulator, unsigned int pw_req)
```

request power budget on a regulator

**Parameters**

- `struct regulator *regulator`: regulator source
- `unsigned int pw_req`: Power requested

**Return**

0 on success or a negative error number on failure.

#### <a id="c-regulator_free_power_budget"></a>`regulator_free_power_budget()`

```c
void regulator_free_power_budget(struct regulator *regulator, unsigned int pw)
```

free power budget on a regulator

**Parameters**

- `struct regulator *regulator`: regulator source
- `unsigned int pw`: Power to be released.

**Return**

Power budget of the regulator in mW.

#### <a id="c-regulator_set_mode"></a>`regulator_set_mode()`

```c
int regulator_set_mode(struct regulator *regulator, unsigned int mode)
```

set regulator operating mode

**Parameters**

- `struct regulator *regulator`: regulator source
- `unsigned int mode`: operating mode - one of the REGULATOR_MODE constants

**Description**

Set regulator operating mode to increase regulator efficiency or improve
regulation performance.

**NOTE**

Regulator system constraints must be set for this regulator before
calling this function otherwise this call will fail.

**Return**

0 on success or a negative error number on failure.

#### <a id="c-regulator_get_mode"></a>`regulator_get_mode()`

```c
unsigned int regulator_get_mode(struct regulator *regulator)
```

get regulator operating mode

**Parameters**

- `struct regulator *regulator`: regulator source

**Description**

Get the current regulator operating mode.

**Return**

Current operating mode as `REGULATOR_MODE_*` values,
or a negative error number on failure.

#### <a id="c-regulator_get_error_flags"></a>`regulator_get_error_flags()`

```c
int regulator_get_error_flags(struct regulator *regulator, unsigned int *flags)
```

get regulator error information

**Parameters**

- `struct regulator *regulator`: regulator source
- `unsigned int *flags`: pointer to store error flags

**Description**

Get the current regulator error information.

**Return**

0 on success or a negative error number on failure.

#### <a id="c-regulator_set_load"></a>`regulator_set_load()`

```c
int regulator_set_load(struct regulator *regulator, int uA_load)
```

set regulator load

**Parameters**

- `struct regulator *regulator`: regulator source
- `int uA_load`: load current

**Description**

Notifies the regulator core of a new device load. This is then used by
DRMS (if enabled by constraints) to set the most efficient regulator
operating mode for the new regulator loading.

Consumer devices notify their supply regulator of the maximum power
they will require (can be taken from device datasheet in the power
consumption tables) when they change operational status and hence power
state. Examples of operational state changes that can affect power
consumption are :-

o Device is opened / closed.
o Device I/O is about to begin or has just finished.
o Device is idling in between work.

This information is also exported via sysfs to userspace.

DRMS will sum the total requested load on the regulator and change
to the most efficient operating mode if platform constraints allow.

**NOTE**

when a regulator consumer requests to have a regulator
disabled then any load that consumer requested no longer counts
toward the total requested load.  If the regulator is re-enabled
then the previously requested load will start counting again.

If a regulator is an always-on regulator then an individual consumer's
load will still be removed if that consumer is fully disabled.

**Return**

0 on success or a negative error number on failure.

#### <a id="c-regulator_allow_bypass"></a>`regulator_allow_bypass()`

```c
int regulator_allow_bypass(struct regulator *regulator, bool enable)
```

allow the regulator to go into bypass mode

**Parameters**

- `struct regulator *regulator`: Regulator to configure
- `bool enable`: enable or disable bypass mode

**Description**

Allow the regulator to go into bypass mode if all other consumers
for the regulator also enable bypass mode and the machine
constraints allow this.  Bypass mode means that the regulator is
simply passing the input directly to the output with no regulation.

**Return**

0 on success or if changing bypass is not possible, or
a negative error number on failure.

#### <a id="c-regulator_register_notifier"></a>`regulator_register_notifier()`

```c
int regulator_register_notifier(struct regulator *regulator, struct notifier_block *nb)
```

register regulator event notifier

**Parameters**

- `struct regulator *regulator`: regulator source
- `struct notifier_block *nb`: notifier block

**Description**

Register notifier block to receive regulator events.

**Return**

0 on success or a negative error number on failure.

#### <a id="c-regulator_unregister_notifier"></a>`regulator_unregister_notifier()`

```c
int regulator_unregister_notifier(struct regulator *regulator, struct notifier_block *nb)
```

unregister regulator event notifier

**Parameters**

- `struct regulator *regulator`: regulator source
- `struct notifier_block *nb`: notifier block

**Description**

Unregister regulator event notifier block.

**Return**

0 on success or a negative error number on failure.

#### <a id="c-regulator_bulk_get"></a>`regulator_bulk_get()`

```c
int regulator_bulk_get(struct device *dev, int num_consumers, struct regulator_bulk_data *consumers)
```

get multiple regulator consumers

**Parameters**

- `struct device *dev`: Device to supply
- `int num_consumers`: Number of consumers to register
- `struct regulator_bulk_data *consumers`: Configuration of consumers; clients are stored here.

**Description**

This helper function allows drivers to get several regulator
consumers in one operation.  If any of the regulators cannot be
acquired then any regulators that were allocated will be freed
before returning to the caller.

**Return**

0 on success or a negative error number on failure.

#### <a id="c-regulator_bulk_enable"></a>`regulator_bulk_enable()`

```c
int regulator_bulk_enable(int num_consumers, struct regulator_bulk_data *consumers)
```

enable multiple regulator consumers

**Parameters**

- `int num_consumers`: Number of consumers
- `struct regulator_bulk_data *consumers`: Consumer data; clients are stored here.

**Description**

This convenience API allows consumers to enable multiple regulator
clients in a single API call.  If any consumers cannot be enabled
then any others that were enabled will be disabled again prior to
return.

**Return**

0 on success or a negative error number on failure.

#### <a id="c-regulator_bulk_disable"></a>`regulator_bulk_disable()`

```c
int regulator_bulk_disable(int num_consumers, struct regulator_bulk_data *consumers)
```

disable multiple regulator consumers

**Parameters**

- `int num_consumers`: Number of consumers
- `struct regulator_bulk_data *consumers`: Consumer data; clients are stored here.

**Description**

This convenience API allows consumers to disable multiple regulator
clients in a single API call.  If any consumers cannot be disabled
then any others that were disabled will be enabled again prior to
return.

**Return**

0 on success or a negative error number on failure.

#### <a id="c-regulator_bulk_force_disable"></a>`regulator_bulk_force_disable()`

```c
int regulator_bulk_force_disable(int num_consumers, struct regulator_bulk_data *consumers)
```

force disable multiple regulator consumers

**Parameters**

- `int num_consumers`: Number of consumers
- `struct regulator_bulk_data *consumers`: Consumer data; clients are stored here.

**Description**

This convenience API allows consumers to forcibly disable multiple regulator
clients in a single API call.

**NOTE**

This should be used for situations when device damage will
likely occur if the regulators are not disabled (e.g. over temp).
Although regulator_force_disable function call for some consumers can
return error numbers, the function is called for all consumers.

**Return**

0 on success or a negative error number on failure.

#### <a id="c-regulator_bulk_free"></a>`regulator_bulk_free()`

```c
void regulator_bulk_free(int num_consumers, struct regulator_bulk_data *consumers)
```

free multiple regulator consumers

**Parameters**

- `int num_consumers`: Number of consumers
- `struct regulator_bulk_data *consumers`: Consumer data; clients are stored here.

**Description**

This convenience API allows consumers to free multiple regulator
clients in a single API call.

#### <a id="c-regulator_notifier_call_chain"></a>`regulator_notifier_call_chain()`

```c
int regulator_notifier_call_chain(struct regulator_dev *rdev, unsigned long event, void *data)
```

call regulator event notifier

**Parameters**

- `struct regulator_dev *rdev`: regulator source
- `unsigned long event`: notifier block
- `void *data`: callback-specific data.

**Description**

Called by regulator drivers to notify clients a regulator event has
occurred.

**Return**

`NOTIFY_DONE`.

#### <a id="c-regulator_mode_to_status"></a>`regulator_mode_to_status()`

```c
int regulator_mode_to_status(unsigned int mode)
```

convert a regulator mode into a status

**Parameters**

- `unsigned int mode`: Mode to convert

**Description**

Convert a regulator mode into a status.

**Return**

`REGULATOR_STATUS_*` value corresponding to given mode.

#### <a id="c-regulator_register"></a>`regulator_register()`

```c
struct regulator_dev * regulator_register(struct device *dev, const struct regulator_desc *regulator_desc, const struct regulator_config *cfg)
```

register regulator

**Parameters**

- `struct device *dev`: the device that drive the regulator
- `const struct regulator_desc *regulator_desc`: regulator to register
- `const struct regulator_config *cfg`: runtime configuration for regulator

**Description**

Called by regulator drivers to register a regulator.

**Return**

Pointer to a valid `struct regulator_dev` on success or
an [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR) encoded negative error number on failure.

#### <a id="c-regulator_unregister"></a>`regulator_unregister()`

```c
void regulator_unregister(struct regulator_dev *rdev)
```

unregister regulator

**Parameters**

- `struct regulator_dev *rdev`: regulator to unregister

**Description**

Called by regulator drivers to unregister a regulator.

#### <a id="c-regulator_has_full_constraints"></a>`regulator_has_full_constraints()`

```c
void regulator_has_full_constraints(void)
```

the system has fully specified constraints

**Parameters**

- `void`: no arguments

**Description**

Calling this function will cause the regulator API to disable all
regulators which have a zero use count and don't have an always_on
constraint in a late_initcall.

The intention is that this will become the default behaviour in a
future kernel release so users are encouraged to use this facility
now.

#### <a id="c-rdev_get_drvdata"></a>`rdev_get_drvdata()`

```c
void * rdev_get_drvdata(struct regulator_dev *rdev)
```

get rdev regulator driver data

**Parameters**

- `struct regulator_dev *rdev`: regulator

**Description**

Get rdev regulator driver private data. This call can be used in the
regulator driver context.

**Return**

Pointer to regulator driver private data.

#### <a id="c-regulator_get_drvdata"></a>`regulator_get_drvdata()`

```c
void * regulator_get_drvdata(struct regulator *regulator)
```

get regulator driver data

**Parameters**

- `struct regulator *regulator`: regulator

**Description**

Get regulator driver private data. This call can be used in the consumer
driver context when non API regulator specific functions need to be called.

**Return**

Pointer to regulator driver private data.

#### <a id="c-regulator_set_drvdata"></a>`regulator_set_drvdata()`

```c
void regulator_set_drvdata(struct regulator *regulator, void *data)
```

set regulator driver data

**Parameters**

- `struct regulator *regulator`: regulator
- `void *data`: data

#### <a id="c-rdev_get_id"></a>`rdev_get_id()`

```c
int rdev_get_id(struct regulator_dev *rdev)
```

get regulator ID

**Parameters**

- `struct regulator_dev *rdev`: regulator

**Return**

Regulator ID for **rdev**.

---

# Reset controller API

_Peios Kernel / Hardware and drivers / Driver development / Clocks, signals and platform services_

> Reset controllers are central units that control the reset signals to multiple peripherals. The reset controller API is split into two parts: the consumer driver interface (API reference), which allows peripheral drivers to request control…

<a id="rst-reset-controller-api"></a>

<!-- SPDX-License-Identifier: GPL-2.0-only -->

<a id="rst-introduction"></a>

## Introduction

Reset controllers are central units that control the reset signals to multiple peripherals. The reset controller API is split into two parts: the [consumer driver interface](<#consumer-driver-interface>) ([API reference](<#reset-consumer-api>)), which allows peripheral drivers to request control over their reset input signals, and the [reset controller driver interface](<#reset-controller-driver-interface>) ([API reference](<#reset-controller-driver-api>)), which is used by drivers for reset controller devices to register their reset controls to provide them to the consumers.

While some reset controller hardware units also implement system restart functionality, restart handlers are out of scope for the reset controller API.

<a id="rst-glossary"></a>

### Glossary

The reset controller API uses these terms with a specific meaning:

Reset line

> Physical reset line carrying a reset signal from a reset controller hardware unit to a peripheral module.

Reset control

> Control method that determines the state of one or multiple reset lines. Most commonly this is a single bit in reset controller register space that either allows direct control over the physical state of the reset line, or is self-clearing and can be used to trigger a predetermined pulse on the reset line. In more complicated reset controls, a single trigger action can launch a carefully timed sequence of pulses on multiple reset lines.

Reset controller

> A hardware module that provides a number of reset controls to control a number of reset lines.

Reset consumer

> Peripheral module or external IC that is put into reset by the signal on a reset line.

<a id="rst-consumer-driver-interface"></a>

## Consumer driver interface

This interface provides an API that is similar to the kernel clock framework. Consumer drivers use get and put operations to acquire and release reset controls. Functions are provided to assert and deassert the controlled reset lines, trigger reset pulses, or to query reset line status.

When requesting reset controls, consumers can use symbolic names for their reset inputs, which are mapped to an actual reset control on an existing reset controller device by the core.

A stub version of this API is provided when the reset controller framework is not in use in order to minimize the need to use ifdefs.

<a id="rst-shared-and-exclusive-resets"></a>

### Shared and exclusive resets

The reset controller API provides either reference counted deassertion and assertion or direct, exclusive control. The distinction between shared and exclusive reset controls is made at the time the reset control is requested, either via devm_reset_control_get_shared() or via devm_reset_control_get_exclusive(). This choice determines the behavior of the API calls made with the reset control.

Shared resets behave similarly to clocks in the kernel clock framework. They provide reference counted deassertion, where only the first deassert, which increments the deassertion reference count to one, and the last assert which decrements the deassertion reference count back to zero, have a physical effect on the reset line.

Exclusive resets on the other hand guarantee direct control. That is, an assert causes the reset line to be asserted immediately, and a deassert causes the reset line to be deasserted immediately.

<a id="rst-assertion-and-deassertion"></a>

### Assertion and deassertion

Consumer drivers use the reset_control_assert() and reset_control_deassert() functions to assert and deassert reset lines. For shared reset controls, calls to the two functions must be balanced.

Note that since multiple consumers may be using a shared reset control, there is no guarantee that calling reset_control_assert() on a shared reset control will actually cause the reset line to be asserted. Consumer drivers using shared reset controls should assume that the reset line may be kept deasserted at all times. The API only guarantees that the reset line can not be asserted as long as any consumer has requested it to be deasserted.

<a id="rst-triggering"></a>

### Triggering

Consumer drivers use reset_control_reset() to trigger a reset pulse on a self-deasserting reset control. In general, these resets can not be shared between multiple consumers, since requesting a pulse from any consumer driver will reset all connected peripherals.

The reset controller API allows requesting self-deasserting reset controls as shared, but for those only the first trigger request causes an actual pulse to be issued on the reset line. All further calls to this function have no effect until all consumers have called reset_control_rearm(). For shared reset controls, calls to the two functions must be balanced. This allows devices that only require an initial reset at any point before the driver is probed or resumed to share a pulsed reset line.

<a id="rst-querying"></a>

### Querying

Only some reset controllers support querying the current status of a reset line, via reset_control_status(). If supported, this function returns a positive non-zero value if the given reset line is asserted. The reset_control_status() function does not accept a [reset control array](<#reset-control-arrays>) handle as its input parameter.

<a id="rst-optional-resets"></a>

### Optional resets

Often peripherals require a reset line on some platforms but not on others. For this, reset controls can be requested as optional using devm_reset_control_get_optional_exclusive() or devm_reset_control_get_optional_shared(). These functions return a NULL pointer instead of an error when the requested reset control is not specified in the device tree. Passing a NULL pointer to the reset_control functions causes them to return quietly without an error.

<a id="rst-reset-control-arrays"></a>

### Reset control arrays

Some drivers need to assert a bunch of reset lines in no particular order. devm_reset_control_array_get() returns an opaque reset control handle that can be used to assert, deassert, or trigger all specified reset controls at once. The reset control API does not guarantee the order in which the individual controls therein are handled.

<a id="rst-reset-controller-driver-interface"></a>

## Reset controller driver interface

Drivers for reset controller modules provide the functionality necessary to assert or deassert reset signals, to trigger a reset pulse on a reset line, or to query its current state. All functions are optional.

<a id="rst-initialization"></a>

### Initialization

Drivers fill a struct `reset_controller_dev` and register it with reset_controller_register() in their probe function. The actual functionality is implemented in callback functions via a struct `reset_control_ops`.

<a id="rst-api-reference"></a>

## API reference

The reset controller API is documented here in two parts: the [reset consumer API](<#reset-consumer-api>) and the [reset controller driver API](<#reset-controller-driver-api>).

<a id="rst-reset-consumer-api"></a>

### Reset consumer API

Reset consumers can control a reset line using an opaque reset control handle, which can be obtained from devm_reset_control_get_exclusive() or devm_reset_control_get_shared(). Given the reset control, consumers can call reset_control_assert() and reset_control_deassert(), trigger a reset pulse using reset_control_reset(), or query the reset line status using reset_control_status().


#### <a id="c-struct-reset_control_bulk_data"></a>`struct reset_control_bulk_data`

Data used for bulk reset control operations.

**Definition**

```c
struct reset_control_bulk_data {
    const char                      *id;
    struct reset_control            *rstc;
};
```

**Members**

- `id`: reset control consumer ID
- `rstc`: struct reset_control * to store the associated reset control

**Description**

The reset APIs provide a series of reset_control_bulk_*() API calls as
a convenience to consumers which require multiple reset controls.
This structure is used to manage data for these calls.

#### <a id="c-enum-reset_control_flags"></a>`enum reset_control_flags`

Flags that can be passed to the reset_control_get functions to determine the type of reset control. These values cannot be OR'd.

**Constants**

- `RESET_CONTROL_EXCLUSIVE`: exclusive, acquired,
- `RESET_CONTROL_EXCLUSIVE_DEASSERTED`: exclusive, acquired, deasserted
- `RESET_CONTROL_EXCLUSIVE_RELEASED`: exclusive, released,
- `RESET_CONTROL_SHARED`: shared
- `RESET_CONTROL_SHARED_DEASSERTED`: shared, deasserted
- `RESET_CONTROL_OPTIONAL_EXCLUSIVE`: optional, exclusive, acquired
- `RESET_CONTROL_OPTIONAL_EXCLUSIVE_DEASSERTED`: optional, exclusive, acquired, deasserted
- `RESET_CONTROL_OPTIONAL_EXCLUSIVE_RELEASED`: optional, exclusive, released
- `RESET_CONTROL_OPTIONAL_SHARED`: optional, shared
- `RESET_CONTROL_OPTIONAL_SHARED_DEASSERTED`: optional, shared, deasserted

#### <a id="c-reset_control_get_exclusive"></a>`reset_control_get_exclusive()`

```c
struct reset_control * reset_control_get_exclusive(struct device *dev, const char *id)
```

Lookup and obtain an exclusive reference to a reset controller.

**Parameters**

- `struct device *dev`: device to be reset by the controller
- `const char *id`: reset line name

**Description**

Returns a struct reset_control or [`IS_ERR()`](/kernel/internals/core-api/kernel-api.md#c-IS_ERR) condition containing errno.
If this function is called more than once for the same reset_control it will
return -EBUSY.

See [`reset_control_get_shared()`](#c-reset_control_get_shared) for details on shared references to
reset-controls.

Use of id names is optional.

#### <a id="c-reset_control_bulk_get_exclusive"></a>`reset_control_bulk_get_exclusive()`

```c
int reset_control_bulk_get_exclusive(struct device *dev, int num_rstcs, struct reset_control_bulk_data *rstcs)
```

Lookup and obtain exclusive references to multiple reset controllers.

**Parameters**

- `struct device *dev`: device to be reset by the controller
- `int num_rstcs`: number of entries in rstcs array
- `struct reset_control_bulk_data *rstcs`: array of struct reset_control_bulk_data with reset line names set

**Description**

Fills the rstcs array with pointers to exclusive reset controls and
returns 0, or an [`IS_ERR()`](/kernel/internals/core-api/kernel-api.md#c-IS_ERR) condition containing errno.

#### <a id="c-reset_control_get_exclusive_released"></a>`reset_control_get_exclusive_released()`

```c
struct reset_control * reset_control_get_exclusive_released(struct device *dev, const char *id)
```

Lookup and obtain a temoprarily exclusive reference to a reset controller.

**Parameters**

- `struct device *dev`: device to be reset by the controller
- `const char *id`: reset line name

**Description**

Returns a struct reset_control or [`IS_ERR()`](/kernel/internals/core-api/kernel-api.md#c-IS_ERR) condition containing errno.
reset-controls returned by this function must be acquired via
[`reset_control_acquire()`](#c-reset_control_acquire) before they can be used and should be released
via [`reset_control_release()`](#c-reset_control_release) afterwards.

Use of id names is optional.

#### <a id="c-reset_control_bulk_get_exclusive_released"></a>`reset_control_bulk_get_exclusive_released()`

```c
int reset_control_bulk_get_exclusive_released(struct device *dev, int num_rstcs, struct reset_control_bulk_data *rstcs)
```

Lookup and obtain temporarily exclusive references to multiple reset controllers.

**Parameters**

- `struct device *dev`: device to be reset by the controller
- `int num_rstcs`: number of entries in rstcs array
- `struct reset_control_bulk_data *rstcs`: array of struct reset_control_bulk_data with reset line names set

**Description**

Fills the rstcs array with pointers to exclusive reset controls and
returns 0, or an [`IS_ERR()`](/kernel/internals/core-api/kernel-api.md#c-IS_ERR) condition containing errno.
reset-controls returned by this function must be acquired via
`reset_control_bulk_acquire()` before they can be used and should be released
via `reset_control_bulk_release()` afterwards.

#### <a id="c-reset_control_bulk_get_optional_exclusive_released"></a>`reset_control_bulk_get_optional_exclusive_released()`

```c
int reset_control_bulk_get_optional_exclusive_released(struct device *dev, int num_rstcs, struct reset_control_bulk_data *rstcs)
```

Lookup and obtain optional temporarily exclusive references to multiple reset controllers.

**Parameters**

- `struct device *dev`: device to be reset by the controller
- `int num_rstcs`: number of entries in rstcs array
- `struct reset_control_bulk_data *rstcs`: array of struct reset_control_bulk_data with reset line names set

**Description**

Optional variant of [`reset_control_bulk_get_exclusive_released()`](#c-reset_control_bulk_get_exclusive_released). If the
requested reset is not specified in the device tree, this function returns 0
instead of an error and missing rtsc is set to NULL.

See [`reset_control_bulk_get_exclusive_released()`](#c-reset_control_bulk_get_exclusive_released) for more information.

#### <a id="c-reset_control_get_shared"></a>`reset_control_get_shared()`

```c
struct reset_control * reset_control_get_shared(struct device *dev, const char *id)
```

Lookup and obtain a shared reference to a reset controller.

**Parameters**

- `struct device *dev`: device to be reset by the controller
- `const char *id`: reset line name

**Description**

Returns a struct reset_control or [`IS_ERR()`](/kernel/internals/core-api/kernel-api.md#c-IS_ERR) condition containing errno.
This function is intended for use with reset-controls which are shared
between hardware blocks.

When a reset-control is shared, the behavior of reset_control_assert /
deassert is changed, the reset-core will keep track of a deassert_count
and only (re-)assert the reset after reset_control_assert has been called
as many times as reset_control_deassert was called. Also see the remark
about shared reset-controls in the reset_control_assert docs.

Calling reset_control_assert without first calling reset_control_deassert
is not allowed on a shared reset control. Calling reset_control_reset is
also not allowed on a shared reset control.

Use of id names is optional.

#### <a id="c-reset_control_bulk_get_shared"></a>`reset_control_bulk_get_shared()`

```c
int reset_control_bulk_get_shared(struct device *dev, int num_rstcs, struct reset_control_bulk_data *rstcs)
```

Lookup and obtain shared references to multiple reset controllers.

**Parameters**

- `struct device *dev`: device to be reset by the controller
- `int num_rstcs`: number of entries in rstcs array
- `struct reset_control_bulk_data *rstcs`: array of struct reset_control_bulk_data with reset line names set

**Description**

Fills the rstcs array with pointers to shared reset controls and
returns 0, or an [`IS_ERR()`](/kernel/internals/core-api/kernel-api.md#c-IS_ERR) condition containing errno.

#### <a id="c-reset_control_get_optional_exclusive"></a>`reset_control_get_optional_exclusive()`

```c
struct reset_control * reset_control_get_optional_exclusive(struct device *dev, const char *id)
```

optional [`reset_control_get_exclusive()`](#c-reset_control_get_exclusive)

**Parameters**

- `struct device *dev`: device to be reset by the controller
- `const char *id`: reset line name

**Description**

Optional variant of [`reset_control_get_exclusive()`](#c-reset_control_get_exclusive). If the requested reset
is not specified in the device tree, this function returns NULL instead of
an error.

See [`reset_control_get_exclusive()`](#c-reset_control_get_exclusive) for more information.

#### <a id="c-reset_control_bulk_get_optional_exclusive"></a>`reset_control_bulk_get_optional_exclusive()`

```c
int reset_control_bulk_get_optional_exclusive(struct device *dev, int num_rstcs, struct reset_control_bulk_data *rstcs)
```

optional [`reset_control_bulk_get_exclusive()`](#c-reset_control_bulk_get_exclusive)

**Parameters**

- `struct device *dev`: device to be reset by the controller
- `int num_rstcs`: number of entries in rstcs array
- `struct reset_control_bulk_data *rstcs`: array of struct reset_control_bulk_data with reset line names set

**Description**

Optional variant of [`reset_control_bulk_get_exclusive()`](#c-reset_control_bulk_get_exclusive). If any of the
requested resets are not specified in the device tree, this function sets
them to NULL instead of returning an error.

See [`reset_control_bulk_get_exclusive()`](#c-reset_control_bulk_get_exclusive) for more information.

#### <a id="c-reset_control_get_optional_shared"></a>`reset_control_get_optional_shared()`

```c
struct reset_control * reset_control_get_optional_shared(struct device *dev, const char *id)
```

optional [`reset_control_get_shared()`](#c-reset_control_get_shared)

**Parameters**

- `struct device *dev`: device to be reset by the controller
- `const char *id`: reset line name

**Description**

Optional variant of [`reset_control_get_shared()`](#c-reset_control_get_shared). If the requested reset
is not specified in the device tree, this function returns NULL instead of
an error.

See [`reset_control_get_shared()`](#c-reset_control_get_shared) for more information.

#### <a id="c-reset_control_bulk_get_optional_shared"></a>`reset_control_bulk_get_optional_shared()`

```c
int reset_control_bulk_get_optional_shared(struct device *dev, int num_rstcs, struct reset_control_bulk_data *rstcs)
```

optional [`reset_control_bulk_get_shared()`](#c-reset_control_bulk_get_shared)

**Parameters**

- `struct device *dev`: device to be reset by the controller
- `int num_rstcs`: number of entries in rstcs array
- `struct reset_control_bulk_data *rstcs`: array of struct reset_control_bulk_data with reset line names set

**Description**

Optional variant of [`reset_control_bulk_get_shared()`](#c-reset_control_bulk_get_shared). If the requested resets
are not specified in the device tree, this function sets them to NULL
instead of returning an error.

See [`reset_control_bulk_get_shared()`](#c-reset_control_bulk_get_shared) for more information.

#### <a id="c-of_reset_control_get_exclusive"></a>`of_reset_control_get_exclusive()`

```c
struct reset_control * of_reset_control_get_exclusive(struct device_node *node, const char *id)
```

Lookup and obtain an exclusive reference to a reset controller.

**Parameters**

- `struct device_node *node`: device to be reset by the controller
- `const char *id`: reset line name

**Description**

Returns a struct reset_control or [`IS_ERR()`](/kernel/internals/core-api/kernel-api.md#c-IS_ERR) condition containing errno.

Use of id names is optional.

#### <a id="c-of_reset_control_get_optional_exclusive"></a>`of_reset_control_get_optional_exclusive()`

```c
struct reset_control * of_reset_control_get_optional_exclusive(struct device_node *node, const char *id)
```

Lookup and obtain an optional exclusive reference to a reset controller.

**Parameters**

- `struct device_node *node`: device to be reset by the controller
- `const char *id`: reset line name

**Description**

Optional variant of [`of_reset_control_get_exclusive()`](#c-of_reset_control_get_exclusive). If the requested reset
is not specified in the device tree, this function returns NULL instead of
an error.

Returns a struct reset_control or [`IS_ERR()`](/kernel/internals/core-api/kernel-api.md#c-IS_ERR) condition containing errno.

Use of id names is optional.

#### <a id="c-of_reset_control_get_shared"></a>`of_reset_control_get_shared()`

```c
struct reset_control * of_reset_control_get_shared(struct device_node *node, const char *id)
```

Lookup and obtain a shared reference to a reset controller.

**Parameters**

- `struct device_node *node`: device to be reset by the controller
- `const char *id`: reset line name

**Description**

When a reset-control is shared, the behavior of reset_control_assert /
deassert is changed, the reset-core will keep track of a deassert_count
and only (re-)assert the reset after reset_control_assert has been called
as many times as reset_control_deassert was called. Also see the remark
about shared reset-controls in the reset_control_assert docs.

Calling reset_control_assert without first calling reset_control_deassert
is not allowed on a shared reset control. Calling reset_control_reset is
also not allowed on a shared reset control.
Returns a struct reset_control or [`IS_ERR()`](/kernel/internals/core-api/kernel-api.md#c-IS_ERR) condition containing errno.

Use of id names is optional.

#### <a id="c-of_reset_control_get_exclusive_by_index"></a>`of_reset_control_get_exclusive_by_index()`

```c
struct reset_control * of_reset_control_get_exclusive_by_index(struct device_node *node, int index)
```

Lookup and obtain an exclusive reference to a reset controller by index.

**Parameters**

- `struct device_node *node`: device to be reset by the controller
- `int index`: index of the reset controller

**Description**

This is to be used to perform a list of resets for a device or power domain
in whatever order. Returns a struct reset_control or [`IS_ERR()`](/kernel/internals/core-api/kernel-api.md#c-IS_ERR) condition
containing errno.

#### <a id="c-of_reset_control_get_shared_by_index"></a>`of_reset_control_get_shared_by_index()`

```c
struct reset_control * of_reset_control_get_shared_by_index(struct device_node *node, int index)
```

Lookup and obtain a shared reference to a reset controller by index.

**Parameters**

- `struct device_node *node`: device to be reset by the controller
- `int index`: index of the reset controller

**Description**

When a reset-control is shared, the behavior of reset_control_assert /
deassert is changed, the reset-core will keep track of a deassert_count
and only (re-)assert the reset after reset_control_assert has been called
as many times as reset_control_deassert was called. Also see the remark
about shared reset-controls in the reset_control_assert docs.

Calling reset_control_assert without first calling reset_control_deassert
is not allowed on a shared reset control. Calling reset_control_reset is
also not allowed on a shared reset control.
Returns a struct reset_control or [`IS_ERR()`](/kernel/internals/core-api/kernel-api.md#c-IS_ERR) condition containing errno.

This is to be used to perform a list of resets for a device or power domain
in whatever order. Returns a struct reset_control or [`IS_ERR()`](/kernel/internals/core-api/kernel-api.md#c-IS_ERR) condition
containing errno.

#### <a id="c-devm_reset_control_get_exclusive"></a>`devm_reset_control_get_exclusive()`

```c
struct reset_control * devm_reset_control_get_exclusive(struct device *dev, const char *id)
```

resource managed [`reset_control_get_exclusive()`](#c-reset_control_get_exclusive)

**Parameters**

- `struct device *dev`: device to be reset by the controller
- `const char *id`: reset line name

**Description**

Managed [`reset_control_get_exclusive()`](#c-reset_control_get_exclusive). For reset controllers returned
from this function, [`reset_control_put()`](#c-reset_control_put) is called automatically on driver
detach.

See [`reset_control_get_exclusive()`](#c-reset_control_get_exclusive) for more information.

#### <a id="c-devm_reset_control_get_exclusive_deasserted"></a>`devm_reset_control_get_exclusive_deasserted()`

```c
struct reset_control * devm_reset_control_get_exclusive_deasserted(struct device *dev, const char *id)
```

resource managed [`reset_control_get_exclusive()`](#c-reset_control_get_exclusive) + [`reset_control_deassert()`](#c-reset_control_deassert)

**Parameters**

- `struct device *dev`: device to be reset by the controller
- `const char *id`: reset line name

**Description**

Managed [`reset_control_get_exclusive()`](#c-reset_control_get_exclusive) + [`reset_control_deassert()`](#c-reset_control_deassert). For reset
controllers returned from this function, [`reset_control_assert()`](#c-reset_control_assert) +
[`reset_control_put()`](#c-reset_control_put) is called automatically on driver detach.

See [`reset_control_get_exclusive()`](#c-reset_control_get_exclusive) for more information.

#### <a id="c-devm_reset_control_bulk_get_exclusive"></a>`devm_reset_control_bulk_get_exclusive()`

```c
int devm_reset_control_bulk_get_exclusive(struct device *dev, int num_rstcs, struct reset_control_bulk_data *rstcs)
```

resource managed [`reset_control_bulk_get_exclusive()`](#c-reset_control_bulk_get_exclusive)

**Parameters**

- `struct device *dev`: device to be reset by the controller
- `int num_rstcs`: number of entries in rstcs array
- `struct reset_control_bulk_data *rstcs`: array of struct reset_control_bulk_data with reset line names set

**Description**

Managed [`reset_control_bulk_get_exclusive()`](#c-reset_control_bulk_get_exclusive). For reset controllers returned
from this function, [`reset_control_put()`](#c-reset_control_put) is called automatically on driver
detach.

See [`reset_control_bulk_get_exclusive()`](#c-reset_control_bulk_get_exclusive) for more information.

#### <a id="c-devm_reset_control_get_exclusive_released"></a>`devm_reset_control_get_exclusive_released()`

```c
struct reset_control * devm_reset_control_get_exclusive_released(struct device *dev, const char *id)
```

resource managed [`reset_control_get_exclusive_released()`](#c-reset_control_get_exclusive_released)

**Parameters**

- `struct device *dev`: device to be reset by the controller
- `const char *id`: reset line name

**Description**

Managed [`reset_control_get_exclusive_released()`](#c-reset_control_get_exclusive_released). For reset controllers
returned from this function, [`reset_control_put()`](#c-reset_control_put) is called automatically on
driver detach.

See [`reset_control_get_exclusive_released()`](#c-reset_control_get_exclusive_released) for more information.

#### <a id="c-devm_reset_control_bulk_get_exclusive_released"></a>`devm_reset_control_bulk_get_exclusive_released()`

```c
int devm_reset_control_bulk_get_exclusive_released(struct device *dev, int num_rstcs, struct reset_control_bulk_data *rstcs)
```

resource managed [`reset_control_bulk_get_exclusive_released()`](#c-reset_control_bulk_get_exclusive_released)

**Parameters**

- `struct device *dev`: device to be reset by the controller
- `int num_rstcs`: number of entries in rstcs array
- `struct reset_control_bulk_data *rstcs`: array of struct reset_control_bulk_data with reset line names set

**Description**

Managed [`reset_control_bulk_get_exclusive_released()`](#c-reset_control_bulk_get_exclusive_released). For reset controllers
returned from this function, [`reset_control_put()`](#c-reset_control_put) is called automatically on
driver detach.

See [`reset_control_bulk_get_exclusive_released()`](#c-reset_control_bulk_get_exclusive_released) for more information.

#### <a id="c-devm_reset_control_get_optional_exclusive_released"></a>`devm_reset_control_get_optional_exclusive_released()`

```c
struct reset_control * devm_reset_control_get_optional_exclusive_released(struct device *dev, const char *id)
```

resource managed `reset_control_get_optional_exclusive_released()`

**Parameters**

- `struct device *dev`: device to be reset by the controller
- `const char *id`: reset line name

**Description**

Managed-and-optional variant of [`reset_control_get_exclusive_released()`](#c-reset_control_get_exclusive_released). For
reset controllers returned from this function, [`reset_control_put()`](#c-reset_control_put) is called
automatically on driver detach.

See [`reset_control_get_exclusive_released()`](#c-reset_control_get_exclusive_released) for more information.

#### <a id="c-devm_reset_control_bulk_get_optional_exclusive_released"></a>`devm_reset_control_bulk_get_optional_exclusive_released()`

```c
int devm_reset_control_bulk_get_optional_exclusive_released(struct device *dev, int num_rstcs, struct reset_control_bulk_data *rstcs)
```

resource managed `reset_control_bulk_optional_get_exclusive_released()`

**Parameters**

- `struct device *dev`: device to be reset by the controller
- `int num_rstcs`: number of entries in rstcs array
- `struct reset_control_bulk_data *rstcs`: array of struct reset_control_bulk_data with reset line names set

**Description**

Managed `reset_control_bulk_optional_get_exclusive_released()`. For reset
controllers returned from this function, [`reset_control_put()`](#c-reset_control_put) is called
automatically on driver detach.

See `reset_control_bulk_optional_get_exclusive_released()` for more information.

#### <a id="c-devm_reset_control_get_shared"></a>`devm_reset_control_get_shared()`

```c
struct reset_control * devm_reset_control_get_shared(struct device *dev, const char *id)
```

resource managed [`reset_control_get_shared()`](#c-reset_control_get_shared)

**Parameters**

- `struct device *dev`: device to be reset by the controller
- `const char *id`: reset line name

**Description**

Managed [`reset_control_get_shared()`](#c-reset_control_get_shared). For reset controllers returned from
this function, [`reset_control_put()`](#c-reset_control_put) is called automatically on driver detach.
See [`reset_control_get_shared()`](#c-reset_control_get_shared) for more information.

#### <a id="c-devm_reset_control_get_shared_deasserted"></a>`devm_reset_control_get_shared_deasserted()`

```c
struct reset_control * devm_reset_control_get_shared_deasserted(struct device *dev, const char *id)
```

resource managed [`reset_control_get_shared()`](#c-reset_control_get_shared) + [`reset_control_deassert()`](#c-reset_control_deassert)

**Parameters**

- `struct device *dev`: device to be reset by the controller
- `const char *id`: reset line name

**Description**

Managed [`reset_control_get_shared()`](#c-reset_control_get_shared) + [`reset_control_deassert()`](#c-reset_control_deassert). For reset
controllers returned from this function, [`reset_control_assert()`](#c-reset_control_assert) +
[`reset_control_put()`](#c-reset_control_put) is called automatically on driver detach.

See [`devm_reset_control_get_shared()`](#c-devm_reset_control_get_shared) for more information.

#### <a id="c-devm_reset_control_bulk_get_shared"></a>`devm_reset_control_bulk_get_shared()`

```c
int devm_reset_control_bulk_get_shared(struct device *dev, int num_rstcs, struct reset_control_bulk_data *rstcs)
```

resource managed [`reset_control_bulk_get_shared()`](#c-reset_control_bulk_get_shared)

**Parameters**

- `struct device *dev`: device to be reset by the controller
- `int num_rstcs`: number of entries in rstcs array
- `struct reset_control_bulk_data *rstcs`: array of struct reset_control_bulk_data with reset line names set

**Description**

Managed [`reset_control_bulk_get_shared()`](#c-reset_control_bulk_get_shared). For reset controllers returned
from this function, [`reset_control_put()`](#c-reset_control_put) is called automatically on driver
detach.

See [`reset_control_bulk_get_shared()`](#c-reset_control_bulk_get_shared) for more information.

#### <a id="c-devm_reset_control_bulk_get_shared_deasserted"></a>`devm_reset_control_bulk_get_shared_deasserted()`

```c
int devm_reset_control_bulk_get_shared_deasserted(struct device *dev, int num_rstcs, struct reset_control_bulk_data *rstcs)
```

resource managed [`reset_control_bulk_get_shared()`](#c-reset_control_bulk_get_shared) + `reset_control_bulk_deassert()`

**Parameters**

- `struct device *dev`: device to be reset by the controller
- `int num_rstcs`: number of entries in rstcs array
- `struct reset_control_bulk_data *rstcs`: array of struct reset_control_bulk_data with reset line names set

**Description**

Managed [`reset_control_bulk_get_shared()`](#c-reset_control_bulk_get_shared) + `reset_control_bulk_deassert()`. For
reset controllers returned from this function, `reset_control_bulk_assert()` +
`reset_control_bulk_put()` are called automatically on driver detach.

See [`devm_reset_control_bulk_get_shared()`](#c-devm_reset_control_bulk_get_shared) for more information.

#### <a id="c-devm_reset_control_get_optional_exclusive"></a>`devm_reset_control_get_optional_exclusive()`

```c
struct reset_control * devm_reset_control_get_optional_exclusive(struct device *dev, const char *id)
```

resource managed [`reset_control_get_optional_exclusive()`](#c-reset_control_get_optional_exclusive)

**Parameters**

- `struct device *dev`: device to be reset by the controller
- `const char *id`: reset line name

**Description**

Managed [`reset_control_get_optional_exclusive()`](#c-reset_control_get_optional_exclusive). For reset controllers
returned from this function, [`reset_control_put()`](#c-reset_control_put) is called automatically on
driver detach.

See [`reset_control_get_optional_exclusive()`](#c-reset_control_get_optional_exclusive) for more information.

#### <a id="c-devm_reset_control_get_optional_exclusive_deasserted"></a>`devm_reset_control_get_optional_exclusive_deasserted()`

```c
struct reset_control * devm_reset_control_get_optional_exclusive_deasserted(struct device *dev, const char *id)
```

resource managed [`reset_control_get_optional_exclusive()`](#c-reset_control_get_optional_exclusive) + [`reset_control_deassert()`](#c-reset_control_deassert)

**Parameters**

- `struct device *dev`: device to be reset by the controller
- `const char *id`: reset line name

**Description**

Managed [`reset_control_get_optional_exclusive()`](#c-reset_control_get_optional_exclusive) + [`reset_control_deassert()`](#c-reset_control_deassert).
For reset controllers returned from this function, [`reset_control_assert()`](#c-reset_control_assert) +
[`reset_control_put()`](#c-reset_control_put) is called automatically on driver detach.

See [`devm_reset_control_get_optional_exclusive()`](#c-devm_reset_control_get_optional_exclusive) for more information.

#### <a id="c-devm_reset_control_bulk_get_optional_exclusive"></a>`devm_reset_control_bulk_get_optional_exclusive()`

```c
int devm_reset_control_bulk_get_optional_exclusive(struct device *dev, int num_rstcs, struct reset_control_bulk_data *rstcs)
```

resource managed [`reset_control_bulk_get_optional_exclusive()`](#c-reset_control_bulk_get_optional_exclusive)

**Parameters**

- `struct device *dev`: device to be reset by the controller
- `int num_rstcs`: number of entries in rstcs array
- `struct reset_control_bulk_data *rstcs`: array of struct reset_control_bulk_data with reset line names set

**Description**

Managed [`reset_control_bulk_get_optional_exclusive()`](#c-reset_control_bulk_get_optional_exclusive). For reset controllers
returned from this function, [`reset_control_put()`](#c-reset_control_put) is called automatically on
driver detach.

See [`reset_control_bulk_get_optional_exclusive()`](#c-reset_control_bulk_get_optional_exclusive) for more information.

#### <a id="c-devm_reset_control_get_optional_shared"></a>`devm_reset_control_get_optional_shared()`

```c
struct reset_control * devm_reset_control_get_optional_shared(struct device *dev, const char *id)
```

resource managed [`reset_control_get_optional_shared()`](#c-reset_control_get_optional_shared)

**Parameters**

- `struct device *dev`: device to be reset by the controller
- `const char *id`: reset line name

**Description**

Managed [`reset_control_get_optional_shared()`](#c-reset_control_get_optional_shared). For reset controllers returned
from this function, [`reset_control_put()`](#c-reset_control_put) is called automatically on driver
detach.

See [`reset_control_get_optional_shared()`](#c-reset_control_get_optional_shared) for more information.

#### <a id="c-devm_reset_control_get_optional_shared_deasserted"></a>`devm_reset_control_get_optional_shared_deasserted()`

```c
struct reset_control * devm_reset_control_get_optional_shared_deasserted(struct device *dev, const char *id)
```

resource managed [`reset_control_get_optional_shared()`](#c-reset_control_get_optional_shared) + [`reset_control_deassert()`](#c-reset_control_deassert)

**Parameters**

- `struct device *dev`: device to be reset by the controller
- `const char *id`: reset line name

**Description**

Managed [`reset_control_get_optional_shared()`](#c-reset_control_get_optional_shared) + [`reset_control_deassert()`](#c-reset_control_deassert). For
reset controllers returned from this function, [`reset_control_assert()`](#c-reset_control_assert) +
[`reset_control_put()`](#c-reset_control_put) is called automatically on driver detach.

See [`devm_reset_control_get_optional_shared()`](#c-devm_reset_control_get_optional_shared) for more information.

#### <a id="c-devm_reset_control_bulk_get_optional_shared"></a>`devm_reset_control_bulk_get_optional_shared()`

```c
int devm_reset_control_bulk_get_optional_shared(struct device *dev, int num_rstcs, struct reset_control_bulk_data *rstcs)
```

resource managed [`reset_control_bulk_get_optional_shared()`](#c-reset_control_bulk_get_optional_shared)

**Parameters**

- `struct device *dev`: device to be reset by the controller
- `int num_rstcs`: number of entries in rstcs array
- `struct reset_control_bulk_data *rstcs`: array of struct reset_control_bulk_data with reset line names set

**Description**

Managed [`reset_control_bulk_get_optional_shared()`](#c-reset_control_bulk_get_optional_shared). For reset controllers
returned from this function, [`reset_control_put()`](#c-reset_control_put) is called automatically on
driver detach.

See [`reset_control_bulk_get_optional_shared()`](#c-reset_control_bulk_get_optional_shared) for more information.

#### <a id="c-devm_reset_control_get_exclusive_by_index"></a>`devm_reset_control_get_exclusive_by_index()`

```c
struct reset_control * devm_reset_control_get_exclusive_by_index(struct device *dev, int index)
```

resource managed [`reset_control_get_exclusive()`](#c-reset_control_get_exclusive)

**Parameters**

- `struct device *dev`: device to be reset by the controller
- `int index`: index of the reset controller

**Description**

Managed [`reset_control_get_exclusive()`](#c-reset_control_get_exclusive). For reset controllers returned from
this function, [`reset_control_put()`](#c-reset_control_put) is called automatically on driver
detach.

See [`reset_control_get_exclusive()`](#c-reset_control_get_exclusive) for more information.

#### <a id="c-devm_reset_control_get_shared_by_index"></a>`devm_reset_control_get_shared_by_index()`

```c
struct reset_control * devm_reset_control_get_shared_by_index(struct device *dev, int index)
```

resource managed reset_control_get_shared

**Parameters**

- `struct device *dev`: device to be reset by the controller
- `int index`: index of the reset controller

**Description**

Managed [`reset_control_get_shared()`](#c-reset_control_get_shared). For reset controllers returned from
this function, [`reset_control_put()`](#c-reset_control_put) is called automatically on driver detach.
See [`reset_control_get_shared()`](#c-reset_control_get_shared) for more information.



#### <a id="c-reset_control_reset"></a>`reset_control_reset()`

```c
int reset_control_reset(struct reset_control *rstc)
```

reset the controlled device

**Parameters**

- `struct reset_control *rstc`: reset controller

**Description**

On a shared reset line the actual reset pulse is only triggered once for the
lifetime of the reset_control instance: for all but the first caller this is
a no-op.
Consumers must not use reset_control_(de)assert on shared reset lines when
reset_control_reset has been used.

If rstc is NULL it is an optional reset and the function will just
return 0.

#### <a id="c-reset_control_rearm"></a>`reset_control_rearm()`

```c
int reset_control_rearm(struct reset_control *rstc)
```

allow shared reset line to be re-triggered"

**Parameters**

- `struct reset_control *rstc`: reset controller

**Description**

On a shared reset line the actual reset pulse is only triggered once for the
lifetime of the reset_control instance, except if this call is used.

Calls to this function must be balanced with calls to reset_control_reset,
a warning is thrown in case triggered_count ever dips below 0.

Consumers must not use reset_control_(de)assert on shared reset lines when
reset_control_reset or reset_control_rearm have been used.

If rstc is NULL the function will just return 0.

#### <a id="c-reset_control_assert"></a>`reset_control_assert()`

```c
int reset_control_assert(struct reset_control *rstc)
```

asserts the reset line

**Parameters**

- `struct reset_control *rstc`: reset controller

**Description**

Calling this on an exclusive reset controller guarantees that the reset
will be asserted. When called on a shared reset controller the line may
still be deasserted, as long as other users keep it so.

For shared reset controls a driver cannot expect the hw's registers and
internal state to be reset, but must be prepared for this to happen.
Consumers must not use reset_control_reset on shared reset lines when
reset_control_(de)assert has been used.

If rstc is NULL it is an optional reset and the function will just
return 0.

#### <a id="c-reset_control_deassert"></a>`reset_control_deassert()`

```c
int reset_control_deassert(struct reset_control *rstc)
```

deasserts the reset line

**Parameters**

- `struct reset_control *rstc`: reset controller

**Description**

After calling this function, the reset is guaranteed to be deasserted.
Consumers must not use reset_control_reset on shared reset lines when
reset_control_(de)assert has been used.

If rstc is NULL it is an optional reset and the function will just
return 0.

#### <a id="c-reset_control_status"></a>`reset_control_status()`

```c
int reset_control_status(struct reset_control *rstc)
```

returns a negative errno if not supported, a positive value if the reset line is asserted, or zero if the reset line is not asserted or if the desc is NULL (optional reset).

**Parameters**

- `struct reset_control *rstc`: reset controller

#### <a id="c-reset_control_acquire"></a>`reset_control_acquire()`

```c
int reset_control_acquire(struct reset_control *rstc)
```

acquires a reset control for exclusive use

**Parameters**

- `struct reset_control *rstc`: reset control

**Description**

This is used to explicitly acquire a reset control for exclusive use. Note
that exclusive resets are requested as acquired by default. In order for a
second consumer to be able to control the reset, the first consumer has to
release it first. Typically the easiest way to achieve this is to call the
[`reset_control_get_exclusive_released()`](#c-reset_control_get_exclusive_released) to obtain an instance of the reset
control. Such reset controls are not acquired by default.

Consumers implementing shared access to an exclusive reset need to follow
a specific protocol in order to work together. Before consumers can change
a reset they must acquire exclusive access using [`reset_control_acquire()`](#c-reset_control_acquire).
After they are done operating the reset, they must release exclusive access
with a call to [`reset_control_release()`](#c-reset_control_release). Consumers are not granted exclusive
access to the reset as long as another consumer hasn't released a reset.

See also: [`reset_control_release()`](#c-reset_control_release)

#### <a id="c-reset_control_release"></a>`reset_control_release()`

```c
void reset_control_release(struct reset_control *rstc)
```

releases exclusive access to a reset control

**Parameters**

- `struct reset_control *rstc`: reset control

**Description**

Releases exclusive access right to a reset control previously obtained by a
call to [`reset_control_acquire()`](#c-reset_control_acquire). Until a consumer calls this function, no
other consumers will be granted exclusive access.

See also: [`reset_control_acquire()`](#c-reset_control_acquire)

#### <a id="c-reset_control_put"></a>`reset_control_put()`

```c
void reset_control_put(struct reset_control *rstc)
```

free the reset controller

**Parameters**

- `struct reset_control *rstc`: reset controller

#### <a id="c-of_reset_control_get_count"></a>`of_reset_control_get_count()`

```c
int of_reset_control_get_count(struct device_node *node)
```

Count number of resets available with a device

**Parameters**

- `struct device_node *node`: device node that contains 'resets'.

**Description**

Returns positive reset count on success, or error number on failure and
on count being zero.

#### <a id="c-of_reset_control_array_get"></a>`of_reset_control_array_get()`

```c
struct reset_control * of_reset_control_array_get(struct device_node *np, enum reset_control_flags flags)
```

Get a list of reset controls using device node.

**Parameters**

- `struct device_node *np`: device node for the device that requests the reset controls array
- `enum reset_control_flags flags`: whether reset controls are shared, optional, acquired

**Description**

Returns pointer to allocated reset_control on success or error on failure

#### <a id="c-devm_reset_control_array_get"></a>`devm_reset_control_array_get()`

```c
struct reset_control * devm_reset_control_array_get(struct device *dev, enum reset_control_flags flags)
```

Resource managed reset control array get

**Parameters**

- `struct device *dev`: device that requests the list of reset controls
- `enum reset_control_flags flags`: whether reset controls are shared, optional, acquired

**Description**

The reset control array APIs are intended for a list of resets
that just have to be asserted or deasserted, without any
requirements on the order.

Returns pointer to allocated reset_control on success or error on failure

#### <a id="c-reset_control_get_count"></a>`reset_control_get_count()`

```c
int reset_control_get_count(struct device *dev)
```

Count number of resets available with a device

**Parameters**

- `struct device *dev`: device for which to return the number of resets

**Description**

Returns positive reset count on success, or error number on failure and
on count being zero.


<a id="rst-reset-controller-driver-api"></a>

### Reset controller driver API

Reset controller drivers are supposed to implement the necessary functions in a static constant structure `reset_control_ops`, allocate and fill out a struct `reset_controller_dev`, and register it using devm_reset_controller_register().


#### <a id="c-struct-reset_control_ops"></a>`struct reset_control_ops`

reset controller driver callbacks

**Definition**

```c
struct reset_control_ops {
    int (*reset)(struct reset_controller_dev *rcdev, unsigned long id);
    int (*assert)(struct reset_controller_dev *rcdev, unsigned long id);
    int (*deassert)(struct reset_controller_dev *rcdev, unsigned long id);
    int (*status)(struct reset_controller_dev *rcdev, unsigned long id);
};
```

**Members**

- `reset`: for self-deasserting resets, does all necessary
  things to reset the device
- `assert`: manually assert the reset line, if supported
- `deassert`: manually deassert the reset line, if supported
- `status`: return the status of the reset line, if supported

#### <a id="c-struct-reset_controller_dev"></a>`struct reset_controller_dev`

reset controller entity that might provide multiple reset controls

**Definition**

```c
struct reset_controller_dev {
    const struct reset_control_ops *ops;
    struct module *owner;
    struct list_head list;
    struct list_head reset_control_head;
    struct device *dev;
    struct device_node *of_node;
    const struct of_phandle_args *of_args;
    int of_reset_n_cells;
    int (*of_xlate)(struct reset_controller_dev *rcdev, const struct of_phandle_args *reset_spec);
    unsigned int nr_resets;
};
```

**Members**

- `ops`: a pointer to device specific struct reset_control_ops
- `owner`: kernel module of the reset controller driver
- `list`: internal list of reset controller devices
- `reset_control_head`: head of internal list of requested reset controls
- `dev`: corresponding driver model device struct
- `of_node`: corresponding device tree node as phandle target
- `of_args`: for reset-gpios controllers: corresponding phandle args with
  of_node and GPIO number complementing of_node; either this or
  of_node should be present
- `of_reset_n_cells`: number of cells in reset line specifiers
- `of_xlate`: translation function to translate from specifier as found in the
  device tree to id as given to the reset control ops, defaults
  to [`of_reset_simple_xlate()`](#c-of_reset_simple_xlate).
- `nr_resets`: number of reset controls in this reset controller device



#### <a id="c-of_reset_simple_xlate"></a>`of_reset_simple_xlate()`

```c
int of_reset_simple_xlate(struct reset_controller_dev *rcdev, const struct of_phandle_args *reset_spec)
```

translate reset_spec to the reset line number

**Parameters**

- `struct reset_controller_dev *rcdev`: a pointer to the reset controller device
- `const struct of_phandle_args *reset_spec`: reset line specifier as found in the device tree

**Description**

This static translation function is used by default if of_xlate in
[`reset_controller_dev`](#c-struct-reset_controller_dev) is not set. It is useful for all reset
controllers with 1:1 mapping, where reset lines can be indexed by number
without gaps.

#### <a id="c-reset_controller_register"></a>`reset_controller_register()`

```c
int reset_controller_register(struct reset_controller_dev *rcdev)
```

register a reset controller device

**Parameters**

- `struct reset_controller_dev *rcdev`: a pointer to the initialized reset controller device

#### <a id="c-reset_controller_unregister"></a>`reset_controller_unregister()`

```c
void reset_controller_unregister(struct reset_controller_dev *rcdev)
```

unregister a reset controller device

**Parameters**

- `struct reset_controller_dev *rcdev`: a pointer to the reset controller device

#### <a id="c-devm_reset_controller_register"></a>`devm_reset_controller_register()`

```c
int devm_reset_controller_register(struct device *dev, struct reset_controller_dev *rcdev)
```

resource managed [`reset_controller_register()`](#c-reset_controller_register)

**Parameters**

- `struct device *dev`: device that is registering this reset controller
- `struct reset_controller_dev *rcdev`: a pointer to the initialized reset controller device

**Description**

Managed [`reset_controller_register()`](#c-reset_controller_register). For reset controllers registered by
this function, [`reset_controller_unregister()`](#c-reset_controller_unregister) is automatically called on
driver detach. See [`reset_controller_register()`](#c-reset_controller_register) for more information.

---

# rfkill - RF kill switch support

_Peios Kernel / Hardware and drivers / Driver development / Clocks, signals and platform services_

> Introduction

<a id="rst-rfkill-rf-kill-switch-support"></a>

<a id="rst-contents"></a>



<a id="rst-introduction"></a>

## Introduction

The rfkill subsystem provides a generic interface for disabling any radio transmitter in the system. When a transmitter is blocked, it shall not radiate any power.

The subsystem also provides the ability to react on button presses and disable all transmitters of a certain type (or all). This is intended for situations where transmitters need to be turned off, for example on aircraft.

The rfkill subsystem has a concept of "hard" and "soft" block, which differ little in their meaning (block == transmitters off) but rather in whether they can be changed or not:

> - - **hard block**
>
>     read-only radio block that cannot be overridden by software
>
> - - **soft block**
>
>     writable radio block (need not be readable) that is set by the system software.

The rfkill subsystem has two parameters, rfkill.default_state and rfkill.master_switch_mode, which are documented in admin-guide/kernel-parameters.rst.

<a id="rst-implementation-details"></a>

## Implementation details

The rfkill subsystem is composed of three main components:

> - the rfkill core,
>
> - the deprecated rfkill-input module (an input layer handler, being replaced by userspace policy code) and
>
> - the rfkill drivers.

The rfkill core provides API for kernel drivers to register their radio transmitter with the kernel, methods for turning it on and off, and letting the system know about hardware-disabled states that may be implemented on the device.

The rfkill core code also notifies userspace of state changes, and provides ways for userspace to query the current states. See the "Userspace support" section below.

When the device is hard-blocked (either by a call to rfkill_set_hw_state() or from query_hw_block), set_block() will be invoked for additional software block, but drivers can ignore the method call since they can use the return value of the function rfkill_set_hw_state() to sync the software state instead of keeping track of calls to set_block(). In fact, drivers should use the return value of rfkill_set_hw_state() unless the hardware actually keeps track of soft and hard block separately.

<a id="rst-kernel-api"></a>

## Kernel API

Drivers for radio transmitters normally implement an rfkill driver.

Platform drivers might implement input devices if the rfkill button is just that, a button. If that button influences the hardware then you need to implement an rfkill driver instead. This also applies if the platform provides a way to turn on/off the transmitter(s).

For some platforms, it is possible that the hardware state changes during suspend/hibernation, in which case it will be necessary to update the rfkill core with the current state at resume time.

To create an rfkill driver, driver's Kconfig needs to have:



```text
depends on RFKILL || !RFKILL
```

to ensure the driver cannot be built-in when rfkill is modular. The \!RFKILL case allows the driver to be built when rfkill is not configured, in which case all rfkill API can still be used but will be provided by static inlines which compile to almost nothing.

Calling rfkill_set_hw_state() when a state change happens is required from rfkill drivers that control devices that can be hard-blocked unless they also assign the poll_hw_block() callback (then the rfkill core will poll the device). Don't do this unless you cannot get the event in any other way.

rfkill provides per-switch LED triggers, which can be used to drive LEDs according to the switch state (LED_FULL when blocked, LED_OFF otherwise).

<a id="rst-userspace-support"></a>

## Userspace support

The recommended userspace interface to use is /dev/rfkill, which is a misc character device that allows userspace to obtain and set the state of rfkill devices and sets of devices. It also notifies userspace about device addition and removal. The API is a simple read/write API that is defined in linux/rfkill.h, with one ioctl that allows turning off the deprecated input handler in the kernel for the transition period.

Except for the one ioctl, communication with the kernel is done via read() and write() of instances of 'struct rfkill_event'. In this structure, the soft and hard block are properly separated (unlike sysfs, see below) and userspace is able to get a consistent snapshot of all rfkill devices in the system. Also, it is possible to switch all rfkill drivers (or all drivers of a specified type) into a state which also updates the default state for hotplugged devices.

After an application opens /dev/rfkill, it can read the current state of all devices. Changes can be obtained by either polling the descriptor for hotplug or state change events or by listening for uevents emitted by the rfkill core framework.

Additionally, each rfkill device is registered in sysfs and emits uevents.

rfkill devices issue uevents (with an action of "change"), with the following environment variables set:



```text
RFKILL_NAME
RFKILL_STATE
RFKILL_TYPE
```

The content of these variables corresponds to the "name", "state" and "type" sysfs files explained above.

For further details consult Documentation/ABI/stable/sysfs-class-rfkill.

---

# TEE (Trusted Execution Environment) driver API

_Peios Kernel / Hardware and drivers / Driver development / Clocks, signals and platform services_

> Kernel provides a TEE bus infrastructure where a Trusted Application is represented as a device identified via Universally Unique Identifier (UUID) and client drivers register a table of supported device UUIDs.

<a id="rst-tee-trusted-execution-environment-driver-api"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Kernel provides a TEE bus infrastructure where a Trusted Application is represented as a device identified via Universally Unique Identifier (UUID) and client drivers register a table of supported device UUIDs.

TEE bus infrastructure registers following APIs:

- **match():**

  iterates over the client driver UUID table to find a corresponding match for device UUID. If a match is found, then this particular device is probed via corresponding probe API registered by the client driver. This process happens whenever a device or a client driver is registered with TEE bus.

- **uevent():**

  notifies user-space (udev) whenever a new device is registered on TEE bus for auto-loading of modularized client drivers.

TEE bus device enumeration is specific to underlying TEE implementation, so it is left open for TEE drivers to provide corresponding implementation.

Then TEE client driver can talk to a matched Trusted Application using APIs listed in include/linux/tee_drv.h.

<a id="rst-tee-client-driver-example"></a>

## TEE client driver example

Suppose a TEE client driver needs to communicate with a Trusted Application having UUID: `ac6a4085-0e82-4c33-bf98-8eb8e118b6c2`, so driver registration snippet would look like:



```text
static const struct tee_client_device_id client_id_table[] = {
        {UUID_INIT(0xac6a4085, 0x0e82, 0x4c33,
                   0xbf, 0x98, 0x8e, 0xb8, 0xe1, 0x18, 0xb6, 0xc2)},
        {}
};

MODULE_DEVICE_TABLE(tee, client_id_table);

static struct tee_client_driver client_driver = {
        .probe          = client_probe,
        .remove         = client_remove,
        .id_table       = client_id_table,
        .driver         = {
                .name           = DRIVER_NAME,
        },
};

module_tee_client_driver(client_driver);
```

---

# WBRF - Wifi Band RFI Mitigations

_Peios Kernel / Hardware and drivers / Driver development / Clocks, signals and platform services_

> Due to electrical and mechanical constraints in certain platform designs there may be likely interference of relatively high-powered harmonics of the GPU memory clocks with local radio module frequency bands used by certain Wifi bands.

<a id="rst-wbrf-wifi-band-rfi-mitigations"></a>

<!-- SPDX-License-Identifier: GPL-2.0-or-later -->

Due to electrical and mechanical constraints in certain platform designs there may be likely interference of relatively high-powered harmonics of the GPU memory clocks with local radio module frequency bands used by certain Wifi bands.

To mitigate possible RFI interference producers can advertise the frequencies in use and consumers can use this information to avoid using these frequencies for sensitive features.

When a platform is known to have this issue with any contained devices, the platform designer will advertise the availability of this feature via ACPI devices with a device specific method (\_DSM). \* Producers with this \_DSM will be able to advertise the frequencies in use. \* Consumers with this \_DSM will be able to register for notifications of frequencies in use.

<a id="rst-some-general-terms"></a>

## Some general terms

Producer: such component who can produce high-powered radio frequency Consumer: such component who can adjust its in-use frequency in response to the radio frequencies of other components to mitigate the possible RFI.

To make the mechanism function, those producers should notify active use of their particular frequencies so that other consumers can make relative internal adjustments as necessary to avoid this resonance.

<a id="rst-acpi-interface"></a>

## ACPI interface

Although initially used by for wifi + dGPU use cases, the ACPI interface can be scaled to any type of device that a platform designer discovers can cause interference.

The GUID used for the \_DSM is 7B7656CF-DC3D-4C1C-83E9-66E721DE3070.

3 functions are available in this \_DSM:

- 0: discover \# of functions available

- 1: record RF bands in use

- 2: retrieve RF bands in use

<a id="rst-driver-programming-interface"></a>

## Driver programming interface


#### <a id="c-acpi_amd_wbrf_add_remove"></a>`acpi_amd_wbrf_add_remove()`

```c
int acpi_amd_wbrf_add_remove(struct device *dev, uint8_t action, struct wbrf_ranges_in_out *in)
```

add or remove the frequency band the device is using

**Parameters**

- `struct device *dev`: device pointer
- `uint8_t action`: remove or add the frequency band into bios
- `struct wbrf_ranges_in_out *in`: input structure containing the frequency band the device is using

**Description**

Broadcast to other consumers the frequency band the device starts
to use. Underneath the surface the information is cached into an
internal buffer first. Then a notification is sent to all those
registered consumers. So then they can retrieve that buffer to
know the latest active frequency bands. Consumers that haven't
yet been registered can retrieve the information from the cache
when they register.

**Return**

0 for success add/remove wifi frequency band.
Returns a negative error code for failure.

#### <a id="c-acpi_amd_wbrf_supported_producer"></a>`acpi_amd_wbrf_supported_producer()`

```c
bool acpi_amd_wbrf_supported_producer(struct device *dev)
```

determine if the WBRF can be enabled for the device as a producer

**Parameters**

- `struct device *dev`: device pointer

**Description**

Check if the platform equipped with necessary implementations to
support WBRF for the device as a producer.

**Return**

true if WBRF is supported, otherwise returns false

#### <a id="c-acpi_amd_wbrf_supported_consumer"></a>`acpi_amd_wbrf_supported_consumer()`

```c
bool acpi_amd_wbrf_supported_consumer(struct device *dev)
```

determine if the WBRF can be enabled for the device as a consumer

**Parameters**

- `struct device *dev`: device pointer

**Description**

Determine if the platform equipped with necessary implementations to
support WBRF for the device as a consumer.

**Return**

true if WBRF is supported, otherwise returns false.

#### <a id="c-amd_wbrf_retrieve_freq_band"></a>`amd_wbrf_retrieve_freq_band()`

```c
int amd_wbrf_retrieve_freq_band(struct device *dev, struct wbrf_ranges_in_out *out)
```

retrieve current active frequency bands

**Parameters**

- `struct device *dev`: device pointer
- `struct wbrf_ranges_in_out *out`: output structure containing all the active frequency bands

**Description**

Retrieve the current active frequency bands which were broadcasted
by other producers. The consumer who calls this API should take
proper actions if any of the frequency band may cause RFI with its
own frequency band used.

**Return**

0 for getting wifi freq band successfully.
Returns a negative error code for failure.

#### <a id="c-amd_wbrf_register_notifier"></a>`amd_wbrf_register_notifier()`

```c
int amd_wbrf_register_notifier(struct notifier_block *nb)
```

register for notifications of frequency band update

**Parameters**

- `struct notifier_block *nb`: driver notifier block

**Description**

The consumer should register itself via this API so that it can get
notified on the frequency band updates from other producers.

**Return**

0 for registering a consumer driver successfully.
Returns a negative error code for failure.

#### <a id="c-amd_wbrf_unregister_notifier"></a>`amd_wbrf_unregister_notifier()`

```c
int amd_wbrf_unregister_notifier(struct notifier_block *nb)
```

unregister for notifications of frequency band update

**Parameters**

- `struct notifier_block *nb`: driver notifier block

**Description**

The consumer should call this API when it is longer interested with
the frequency band updates from other producers. Usually, this should
be performed during driver cleanup.

**Return**

0 for unregistering a consumer driver.
Returns a negative error code for failure.


<a id="rst-sample-usage"></a>

## Sample Usage

The expected flow for the producers: 1. During probe, call `acpi_amd_wbrf_supported_producer` to check if WBRF can be enabled for the device. 2. On using some frequency band, call `acpi_amd_wbrf_add_remove` with 'add' param to get other consumers properly notified. 3. Or on stopping using some frequency band, call `acpi_amd_wbrf_add_remove` with 'remove' param to get other consumers notified.

The expected flow for the consumers: 1. During probe, call `acpi_amd_wbrf_supported_consumer` to check if WBRF can be enabled for the device. 2. Call `amd_wbrf_register_notifier` to register for notification of frequency band change(add or remove) from other producers. 3. Call the `amd_wbrf_retrieve_freq_band` initially to retrieve current active frequency bands considering some producers may broadcast such information before the consumer is up. 4. On receiving a notification for frequency band change, run `amd_wbrf_retrieve_freq_band` again to retrieve the latest active frequency bands. 5. During driver cleanup, call `amd_wbrf_unregister_notifier` to unregister the notifier.

---

# WMI Driver API

_Peios Kernel / Hardware and drivers / Driver development / Clocks, signals and platform services_

> The WMI driver core supports a more modern bus-based interface for interacting with WMI devices, and an older GUID-based interface. The latter interface is considered to be deprecated, so new WMI drivers should generally avoid it since it…

<a id="rst-wmi-driver-api"></a>

<!-- SPDX-License-Identifier: GPL-2.0-or-later -->

The WMI driver core supports a more modern bus-based interface for interacting with WMI devices, and an older GUID-based interface. The latter interface is considered to be deprecated, so new WMI drivers should generally avoid it since it has some issues with multiple WMI devices sharing the same GUID. The modern bus-based interface instead maps each WMI device to a `struct wmi_device <wmi_device>`, so it supports WMI devices sharing the same GUID. Drivers can then register a `struct wmi_driver <wmi_driver>` which will be bound to compatible WMI devices by the driver core.


#### <a id="c-struct-wmi_device"></a>`struct wmi_device`

WMI device structure

**Definition**

```c
struct wmi_device {
    struct device dev;
    bool setable;
    const char *driver_override;
};
```

**Members**

- `dev`: Device associated with this WMI device
- `setable`: True for devices implementing the Set Control Method
- `driver_override`: Driver name to force a match; do not set directly,
  because core frees it; use [`driver_set_override()`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-driver_set_override) to
  set or clear it.

**Description**

This represents WMI devices discovered by the WMI driver core.

#### <a id="c-to_wmi_device"></a>`to_wmi_device()`

```c
to_wmi_device(device)
```

Helper macro to cast a device to a wmi_device

**Parameters**

- `device`: device struct

**Description**

Cast a struct device to a struct wmi_device.

#### <a id="c-struct-wmi_buffer"></a>`struct wmi_buffer`

WMI data buffer

**Definition**

```c
struct wmi_buffer {
    size_t length;
    void *data;
};
```

**Members**

- `length`: Buffer length in bytes
- `data`: Pointer to the buffer content

**Description**

This structure is used to exchange data with the WMI driver core.

#### <a id="c-struct-wmi_string"></a>`struct wmi_string`

WMI string representation

**Definition**

```c
struct wmi_string {
    __le16 length;
    __le16 chars[];
};
```

**Members**

- `length`: Size of **chars** in bytes
- `chars`: UTF16-LE characters with optional nul termination and padding

**Description**

This structure is used when exchanging string data over the WMI interface.

#### <a id="c-struct-wmi_driver"></a>`struct wmi_driver`

WMI driver structure

**Definition**

```c
struct wmi_driver {
    struct device_driver driver;
    const struct wmi_device_id *id_table;
    bool no_notify_data;
    bool no_singleton;
    int (*probe)(struct wmi_device *wdev, const void *context);
    void (*remove)(struct wmi_device *wdev);
    void (*shutdown)(struct wmi_device *wdev);
    void (*notify)(struct wmi_device *device, union acpi_object *data);
    void (*notify_new)(struct wmi_device *device, const struct wmi_buffer *data);
};
```

**Members**

- `driver`: Driver model structure
- `id_table`: List of WMI GUIDs supported by this driver
- `no_notify_data`: Driver supports WMI events which provide no event data
- `no_singleton`: Driver can be instantiated multiple times
- `probe`: Callback for device binding
- `remove`: Callback for device unbinding
- `shutdown`: Callback for device shutdown
- `notify`: Callback for receiving WMI events (deprecated)
- `notify_new`: Callback for receiving WMI events

**Description**

This represents WMI drivers which handle WMI devices. The data inside the buffer
passed to the **notify_new** callback is guaranteed to be aligned on a 8-byte boundary.

#### <a id="c-to_wmi_driver"></a>`to_wmi_driver()`

```c
to_wmi_driver(drv)
```

Helper macro to cast a driver to a wmi_driver

**Parameters**

- `drv`: driver struct

**Description**

Cast a struct device_driver to a struct wmi_driver.

#### <a id="c-wmi_driver_register"></a>`wmi_driver_register()`

```c
wmi_driver_register(driver)
```

Helper macro to register a WMI driver

**Parameters**

- `driver`: wmi_driver struct

**Description**

Helper macro for registering a WMI driver. It automatically passes
THIS_MODULE to the underlying function.

#### <a id="c-module_wmi_driver"></a>`module_wmi_driver()`

```c
module_wmi_driver(__wmi_driver)
```

Helper macro to register/unregister a WMI driver

**Parameters**

- `__wmi_driver`: wmi_driver struct

**Description**

Helper macro for WMI drivers which do not do anything special in module
init/exit. This eliminates a lot of boilerplate. Each module may only
use this macro once, and calling it replaces [`module_init()`](/kernel/hardware/driver-api/fundamentals/basics.md#c-module_init) and [`module_exit()`](/kernel/hardware/driver-api/fundamentals/basics.md#c-module_exit).



#### <a id="c-wmi_string_to_utf8s"></a>`wmi_string_to_utf8s()`

```c
ssize_t wmi_string_to_utf8s(const struct wmi_string *str, u8 *dst, size_t length)
```

Convert a WMI string into a UTF8 string.

**Parameters**

- `const struct wmi_string *str`: WMI string representation
- `u8 *dst`: Buffer to fill with UTF8 characters
- `size_t length`: Length of the destination buffer

**Description**

Convert as WMI string into a standard UTF8 string. The conversion will stop
once a NUL character is detected or when the buffer is full. Any invalid UTF16
characters will be ignored. The resulting UTF8 string will always be NUL-terminated
when this function returns successfully.

**Return**

Length of the resulting UTF8 string or negative errno code on failure.

#### <a id="c-wmi_string_from_utf8s"></a>`wmi_string_from_utf8s()`

```c
ssize_t wmi_string_from_utf8s(struct wmi_string *str, size_t max_chars, const u8 *src, size_t src_length)
```

Convert a UTF8 string into a WMI string.

**Parameters**

- `struct wmi_string *str`: WMI string representation
- `size_t max_chars`: Maximum number of UTF16 code points to store inside the WMI string
- `const u8 *src`: UTF8 string to convert
- `size_t src_length`: Length of the source string without any trailing NUL-characters

**Description**

Convert a UTF8 string into a WMI string. The conversion will stop when the WMI string is
full. The resulting WMI string will always be NUL-terminated and have its length field set
to and appropriate value when this function returns successfully.

**Return**

Number of UTF16 code points inside the WMI string or negative errno code on failure.



#### <a id="c-wmi_instance_count"></a>`wmi_instance_count()`

```c
int wmi_instance_count(const char *guid_string)
```

Get number of WMI object instances

**Parameters**

- `const char *guid_string`: 36 char string of the form fa50ff2b-f2e8-45de-83fa-65417f2f49ba

**Description**

Get the number of WMI object instances.

**Return**

Number of WMI object instances or negative error code.

#### <a id="c-wmidev_instance_count"></a>`wmidev_instance_count()`

```c
u8 wmidev_instance_count(struct wmi_device *wdev)
```

Get number of WMI object instances

**Parameters**

- `struct wmi_device *wdev`: A wmi bus device from a driver

**Description**

Get the number of WMI object instances.

**Return**

Number of WMI object instances.

#### <a id="c-wmi_evaluate_method"></a>`wmi_evaluate_method()`

```c
acpi_status wmi_evaluate_method(const char *guid_string, u8 instance, u32 method_id, const struct acpi_buffer *in, struct acpi_buffer *out)
```

Evaluate a WMI method (deprecated)

**Parameters**

- `const char *guid_string`: 36 char string of the form fa50ff2b-f2e8-45de-83fa-65417f2f49ba
- `u8 instance`: Instance index
- `u32 method_id`: Method ID to call
- `const struct acpi_buffer *in`: Mandatory buffer containing input for the method call
- `struct acpi_buffer *out`: Empty buffer to return the method results

**Description**

Call an ACPI-WMI method, the caller must free **out**.

**Return**

acpi_status signaling success or error.

#### <a id="c-wmidev_evaluate_method"></a>`wmidev_evaluate_method()`

```c
acpi_status wmidev_evaluate_method(struct wmi_device *wdev, u8 instance, u32 method_id, const struct acpi_buffer *in, struct acpi_buffer *out)
```

Evaluate a WMI method (deprecated)

**Parameters**

- `struct wmi_device *wdev`: A wmi bus device from a driver
- `u8 instance`: Instance index
- `u32 method_id`: Method ID to call
- `const struct acpi_buffer *in`: Mandatory buffer containing input for the method call
- `struct acpi_buffer *out`: Empty buffer to return the method results

**Description**

Call an ACPI-WMI method, the caller must free **out**.

**Return**

acpi_status signaling success or error.

#### <a id="c-wmidev_invoke_method"></a>`wmidev_invoke_method()`

```c
int wmidev_invoke_method(struct wmi_device *wdev, u8 instance, u32 method_id, const struct wmi_buffer *in, struct wmi_buffer *out)
```

Invoke a WMI method

**Parameters**

- `struct wmi_device *wdev`: A wmi bus device from a driver
- `u8 instance`: Instance index
- `u32 method_id`: Method ID to call
- `const struct wmi_buffer *in`: Mandatory WMI buffer containing input for the method call
- `struct wmi_buffer *out`: Optional WMI buffer to return the method results

**Description**

Invoke a WMI method, the caller must free the resulting data inside **out**.
Said data is guaranteed to be aligned on a 8-byte boundary.

**Return**

0 on success or negative error code on failure.

#### <a id="c-wmi_query_block"></a>`wmi_query_block()`

```c
acpi_status wmi_query_block(const char *guid_string, u8 instance, struct acpi_buffer *out)
```

Return contents of a WMI block (deprecated)

**Parameters**

- `const char *guid_string`: 36 char string of the form fa50ff2b-f2e8-45de-83fa-65417f2f49ba
- `u8 instance`: Instance index
- `struct acpi_buffer *out`: Empty buffer to return the contents of the data block to

**Description**

Query a ACPI-WMI block, the caller must free **out**.

**Return**

ACPI object containing the content of the WMI block.

#### <a id="c-wmidev_block_query"></a>`wmidev_block_query()`

```c
union acpi_object * wmidev_block_query(struct wmi_device *wdev, u8 instance)
```

Return contents of a WMI block (deprectated)

**Parameters**

- `struct wmi_device *wdev`: A wmi bus device from a driver
- `u8 instance`: Instance index

**Description**

Query an ACPI-WMI block, the caller must free the result.

**Return**

ACPI object containing the content of the WMI block.

#### <a id="c-wmidev_query_block"></a>`wmidev_query_block()`

```c
int wmidev_query_block(struct wmi_device *wdev, u8 instance, struct wmi_buffer *out)
```

Return contents of a WMI data block

**Parameters**

- `struct wmi_device *wdev`: A wmi bus device from a driver
- `u8 instance`: Instance index
- `struct wmi_buffer *out`: WMI buffer to fill

**Description**

Query a WMI data block, the caller must free the resulting data inside **out**.
Said data is guaranteed to be aligned on a 8-byte boundary.

**Return**

0 on success or a negative error code on failure.

#### <a id="c-wmi_set_block"></a>`wmi_set_block()`

```c
acpi_status wmi_set_block(const char *guid_string, u8 instance, const struct acpi_buffer *in)
```

Write to a WMI block (deprecated)

**Parameters**

- `const char *guid_string`: 36 char string of the form fa50ff2b-f2e8-45de-83fa-65417f2f49ba
- `u8 instance`: Instance index
- `const struct acpi_buffer *in`: Buffer containing new values for the data block

**Description**

Write the contents of the input buffer to an ACPI-WMI data block.

**Return**

acpi_status signaling success or error.

#### <a id="c-wmidev_block_set"></a>`wmidev_block_set()`

```c
acpi_status wmidev_block_set(struct wmi_device *wdev, u8 instance, const struct acpi_buffer *in)
```

Write to a WMI block (deprecated)

**Parameters**

- `struct wmi_device *wdev`: A wmi bus device from a driver
- `u8 instance`: Instance index
- `const struct acpi_buffer *in`: Buffer containing new values for the data block

**Description**

Write contents of the input buffer to an ACPI-WMI data block.

**Return**

acpi_status signaling success or error.

#### <a id="c-wmidev_set_block"></a>`wmidev_set_block()`

```c
int wmidev_set_block(struct wmi_device *wdev, u8 instance, const struct wmi_buffer *in)
```

Write to a WMI data block

**Parameters**

- `struct wmi_device *wdev`: A wmi bus device from a driver
- `u8 instance`: Instance index
- `const struct wmi_buffer *in`: WMI buffer containing new values for the data block

**Description**

Write the content of **in** into a WMI data block.

**Return**

0 on success or negative error code on failure.

#### <a id="c-wmi_install_notify_handler"></a>`wmi_install_notify_handler()`

```c
acpi_status wmi_install_notify_handler(const char *guid, wmi_notify_handler handler, void *data)
```

Register handler for WMI events (deprecated)

**Parameters**

- `const char *guid`: 36 char string of the form fa50ff2b-f2e8-45de-83fa-65417f2f49ba
- `wmi_notify_handler handler`: Function to handle notifications
- `void *data`: Data to be returned to handler when event is fired

**Description**

Register a handler for events sent to the ACPI-WMI mapper device.

**Return**

acpi_status signaling success or error.

#### <a id="c-wmi_remove_notify_handler"></a>`wmi_remove_notify_handler()`

```c
acpi_status wmi_remove_notify_handler(const char *guid)
```

Unregister handler for WMI events (deprecated)

**Parameters**

- `const char *guid`: 36 char string of the form fa50ff2b-f2e8-45de-83fa-65417f2f49ba

**Description**

Unregister handler for events sent to the ACPI-WMI mapper device.

**Return**

acpi_status signaling success or error.

#### <a id="c-wmi_has_guid"></a>`wmi_has_guid()`

```c
bool wmi_has_guid(const char *guid_string)
```

Check if a GUID is available

**Parameters**

- `const char *guid_string`: 36 char string of the form fa50ff2b-f2e8-45de-83fa-65417f2f49ba

**Description**

Check if a given GUID is defined by _WDG.

**Return**

True if GUID is available, false otherwise.

#### <a id="c-wmi_get_acpi_device_uid"></a>`wmi_get_acpi_device_uid()`

```c
char * wmi_get_acpi_device_uid(const char *guid_string)
```

Get _UID name of ACPI device that defines GUID (deprecated)

**Parameters**

- `const char *guid_string`: 36 char string of the form fa50ff2b-f2e8-45de-83fa-65417f2f49ba

**Description**

Find the _UID of ACPI device associated with this WMI GUID.

**Return**

The ACPI _UID field value or NULL if the WMI GUID was not found.

#### <a id="c-wmi_driver_unregister"></a>`wmi_driver_unregister()`

```c
void wmi_driver_unregister(struct wmi_driver *driver)
```

Unregister a WMI driver

**Parameters**

- `struct wmi_driver *driver`: WMI driver to unregister

**Description**

Unregisters a WMI driver from the WMI bus.
